How do I read and parse an XML file in C#?

后端 未结 11 2133
庸人自扰
庸人自扰 2020-11-21 23:03

How do I read and parse an XML file in C#?

11条回答
  •  伪装坚强ぢ
    2020-11-21 23:49

    XmlDocument to read an XML from string or from file.

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

    or

    doc.LoadXml("something");
    

    then find a node below it ie like this

    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
    }
    

    then read the text inside that node like this

    string text = node.InnerText;
    

    or read an attribute

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

    Always check for null on Attributes["something"] since it will be null if the attribute does not exist.

提交回复
热议问题