ASP.NET XmlDocument类详解

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

            Console.WriteLine(doc.SelectSingleNode("Article").OwnerDocument);   //获取该节点所属的XmlDocument
            XmlNode xn = doc.SelectSingleNode("Article").LastChild.ParentNode;  //ParentNode获取直接父节点。
            Console.WriteLine(xn.Name); //输出 Article

            Console.WriteLine(doc.PreserveWhitespace);  //是否保留空白    输出False
            XmlNode xn1 = doc.SelectSingleNode("Article").LastChild.PreviousSibling;
            Console.WriteLine(xn1.Name);    //输出length 的确是最后一个节点的前一个节点。

            Console.ReadKey();
        }

    为了更加好的展示一些属性,现在将xml换成这样:

<?xml version="1.0" encoding="utf-8" ?>
<h:Article xmlns:h = "http://www.xxx.com/">
  <!--默认命名空间-->
  <h:author age="30">张三</h:author>
  <h:length>12000</h:length>
  <h:price>42</h:price>
</h:Article>

代码如下:

static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:UsersAdministratorDesktopConsoleApplication1ConsoleApplication1Test.xml");
            XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
            xnm.AddNamespace("h", "http://www.xxx.com/");
            XmlNode Article = doc.SelectSingleNode("h:Article", xnm);
            string namespace1 = Article.InnerText;
            Console.WriteLine(namespace1);      //输出 张三 12000 30

            Console.WriteLine(Article.Prefix);  //输出 h  获取当前节点的前缀
            Console.WriteLine(Article.NamespaceURI);    //输出 http://www.xxx.com/123  获取当前节点所在的命名空间

            Console.WriteLine(Article.FirstChild.Name + "---" + Article.FirstChild.Value + "---" + Article.FirstChild.LocalName);