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


当前回答

如果您想从XML文件中检索特定的值

 XmlDocument _LocalInfo_Xml = new XmlDocument();
            _LocalInfo_Xml.Load(fileName);
            XmlElement _XmlElement;
            _XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
            string Value = _XmlElement.InnerText;

其他回答

下面是另一种使用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"]是否为空,因为如果属性不存在,它将为空。

有很多方法,一些:

XmlSerializer。使用带有目标模式的类 如果您想读取,请使用XmlSerializer 将Xml中的数据加载到 类的实例。 linq2xml XmlTextReader。 XmlDocument XPathDocument(只读访问)

如果您想从XML文件中检索特定的值

 XmlDocument _LocalInfo_Xml = new XmlDocument();
            _LocalInfo_Xml.Load(fileName);
            XmlElement _XmlElement;
            _XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
            string Value = _XmlElement.InnerText;