更新时间:2023-02-14 09:19:17
XmlDocument 从字符串或文件中读取 XML.
XmlDocument to read an XML from string or from file.
XmlDocument doc = new XmlDocument();
doc.Load("c:\temp.xml");
或
doc.LoadXml("<xml>something</xml>");
然后在它下面找到一个节点,就像这样
then find a node below it ie like this
XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
或
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;
或读取属性
string attr = node.Attributes["theattributename"]?.InnerText
始终检查 Attributes["something"] 是否为 null,因为如果该属性不存在,它将为 null.
Always check for null on Attributes["something"] since it will be null if the attribute does not exist.