如何在c#中读取和解析XML文件?


当前回答

下面是另一种使用Cinchoo ETL的方法,它是一个开源库,可以用很少的代码行解析xml文件。

using (var r = ChoXmlReader<Item>.LoadText(xml)
       .WithXPath("//item")
      )
{
    foreach (var rec in r)
        rec.Print();
}

public class Item
{
    public string Name { get; set; }
    public string ProtectionLevel { get; set; }
    public string Description { get; set; }
}

样本提琴:https://dotnetfiddle.net/otYq5j

免责声明:我是这个库的作者。

其他回答

例如,检查XmlTextReader类。

XmlDocument从字符串或文件中读取XML。

using System.Xml;

XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");

or

doc.LoadXml("<xml>something</xml>");

然后在它下面找到一个节点,就像这样

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");

or

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
}

然后像这样读取节点内的文本

string text = node.InnerText;

或者读取属性

string attr = node.Attributes["theattributename"]?.InnerText

总是检查Attributes["something"]是否为空,因为如果属性不存在,它将为空。

下面是另一种使用Cinchoo ETL的方法,它是一个开源库,可以用很少的代码行解析xml文件。

using (var r = ChoXmlReader<Item>.LoadText(xml)
       .WithXPath("//item")
      )
{
    foreach (var rec in r)
        rec.Print();
}

public class Item
{
    public string Name { get; set; }
    public string ProtectionLevel { get; set; }
    public string Description { get; set; }
}

样本提琴:https://dotnetfiddle.net/otYq5j

免责声明:我是这个库的作者。

LINQ to XML示例:

// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");


// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
            where (int)c.Attribute("id") < 4
            select c.Element("firstName").Value + " " +
                   c.Element("lastName").Value;


foreach (string name in query)
{
    Console.WriteLine("Contact's Full Name: {0}", name);
}

参考:LINQ到XML在MSDN

public void ReadXmlFile()
{
    string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
    XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
    while (reader.Read())
    {
        switch (reader.NodeType)
        {
            case XmlNodeType.Element:
                break;
            case XmlNodeType.Text:
                columnNames.Add(reader.Value);
                break;
            case XmlNodeType.EndElement:
                break;
        }
    }
}

可以避免使用第一个语句,只在XmlTextReader的构造函数中指定路径名。