https://docs.microsoft.com/zh-cn/dotnet/api/system.xml.xmldocument?view=netframework-4.8
您可以使用属性来浏览 XML 文档。 但在使用其中任何一个之前,让我们快速回顾几个术语。 文档由节点组成。 每个节点在其上都有一个直接的父节点。 唯一没有父节点的节点是文档根,因为它是顶级节点。 大多数节点可以有子节点,子节点直接位于其下。 处于相同级别的节点是同级节点。
下面的示例演示如何获取根节点,跳转到根节点的第一个子节点,访问其任何子节点,返回到父节点,然后在同级节点之间导航。
从根节点开始
此示例获取根节点,然后使用该节点将文档内容输出到控制台。
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<?xml version=‘1.0‘ ?>" + "<book genre=‘novel‘ ISBN=‘1-861001-57-5‘>" + "<title>Pride And Prejudice</title>" + "</book>"); //Display the document element. Console.WriteLine(doc.DocumentElement.OuterXml); } }
获取子节点
此示例跳转到根节点的第一个子节点,然后循环访问该节点的子节点(如果存在)。
1 using System; 2 using System.IO; 3 using System.Xml; 4 5 public class Sample { 6 7 public static void Main() { 8 9 XmlDocument doc = new XmlDocument(); 10 doc.LoadXml("<book ISBN=‘1-861001-57-5‘>" + 11 "<title>Pride And Prejudice</title>" + 12 "<price>19.95</price>" + 13 "</book>"); 14 15 XmlNode root = doc.FirstChild; 16 17 //Display the contents of the child nodes. 18 if (root.HasChildNodes) 19 { 20 for (int i=0; i<root.ChildNodes.Count; i++) 21 { 22 Console.WriteLine(root.ChildNodes[i].InnerText); 23 } 24 } 25 } 26 }
原文:https://www.cnblogs.com/ein-key5205/p/12363911.html