将 XML 加载到文档对象模型中
XmlDocument doc = new XmlDocument();
try {
doc.Load("booksData.xml");
}
catch (System.IO.FileNotFoundException){
}
获取子节点
XmlNode root = doc.FirstChild;
if (root.HasChildNodes)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
Console.WriteLine(root.ChildNodes[i].InnerText);
}
}
返回到父节点
使用 ParentNode 属性。
获取节点集合
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("descendant::book[author/last-name='Austen']");
//Change the price on the books.
foreach (XmlNode book in nodeList)
{
book.LastChild.InnerText = "15.95";
}
Console.WriteLine("Display the modified XML document....");
doc.Save(Console.Out);