ASP.NET XmlDocument类详解

2019-05-23 04:05:27刘景俊

NextSibling    下一个兄弟节点
FirstChild     第一个子节点
LastChild     最后一个子节点
ChildNodes    子节点集合
ParentNode     父节点

代码示例:

xml文档:


<?xml version="1.0" encoding="utf-8" ?>
<Article>
  <author age="30">张三</author>
  <length>12000</length>
  <price>42</price>
</Article>

代码:

static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:UsersAdministratorDesktopConsoleApplication1ConsoleApplication1Test.xml");
            //先获取一个唯一的Article节点,再获取其下的第一个子节点 然后再获取该节点下的属性集合
            XmlAttributeCollection xc = doc.SelectSingleNode("Article").FirstChild.Attributes;
            string age = xc[0].Value;   //不过是一个定制的集合罢了,还是集合那套东西 //string age = xc["age"].Value; 支持两种索引访问
            Console.WriteLine(age);     //输出30

            string baseuri = doc.SelectSingleNode("Article").FirstChild.BaseURI;   
            Console.WriteLine(baseuri);     //输出 file:///C:UsersAdministratorDesktopConsoleApplication1ConsoleApplication1Test.xml

            XmlNodeList listNode = doc.SelectSingleNode("Article").ChildNodes;  //获取Article节点下的所有节点列表
            for (int i = 0; i < listNode.Count;i++ )    //XmlNodeList不支持foreach遍历,只能用for
            {
                Console.Write(listNode[i].Name + " : " + listNode[i].InnerText);    //输出 author:张三 length:12000 price:30    Name获取的是限定名,也就是标记名称
            }

            XmlElement xe = doc.DocumentElement;    //获取根节点
            Console.WriteLine(xe.Name);     //输出 Article