.net解析带命名空间的xml写法

前端之家收集整理的这篇文章主要介绍了.net解析带命名空间的xml写法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

先上xml

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <SendExResp xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:office:spreadsheet">
  3. <PayCount>1</PayCount>
  4. <BlackWords />
  5. <ErrorMobiles />
  6. <BlackMobiles />
  7. <BatchSendID>00000000-0000-0000-0000-000000000000</BatchSendID>
  8. <Result>aaa</Result>
  9. <ErrorDesc>成功</ErrorDesc>
  10. </SendExResp>

需要注意,xmlns后面跟:**与不跟,读取时是不同的,看后台代码

  1. String path = System.AppDomain.CurrentDomain.BaseDirectory + "//return.xml";
  2.  
  3. XmlDocument xmldoc = new XmlDocument();
  4. xmldoc.Load(path);
  5.  
  6. XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmldoc.NaMetable); //namespace
  7. namespaceManager.AddNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
  8. namespaceManager.AddNamespace("xsd","http://www.w3.org/2001/XMLSchema");
  9. namespaceManager.AddNamespace("d","urn:schemas-microsoft-com:office:spreadsheet");
  10. XmlNode node = xmldoc.SelectSingleNode("descendant::d:Result",namespaceManager);
  11.  
  12. if (node != null)
  13. {
  14. string s = node.InnerText;
  15. }
如果命 名空间都是xmlns:***这种的,写xmlpath的时候,就不需要带默认命名空间,例如上面的d:,可以直接用//SendExResp/Result就能取到这个节点的值,但是因为有一个命 名空间xmlns="urn:schemas-microsoft-com:office:spreadsheet",xmlns后面没有跟:***,这时,就要把这个默认的命名空间给加在xml路径上。

descendant::表示取这个命名空间下的所有某个名称的节点,该写法参考了微软的官方说明,地址:http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectsinglenode.aspx

怕有时候微软网站打不开,把它的代码粘在下面:

The example uses the file,newbooks.xml,as input.

  1. <?xml version='1.0'?>
  2. <bookstore xmlns="urn:newbooks-schema">
  3. <book genre="novel" style="hardcover">
  4. <title>The Handmaid's Tale</title>
  5. <author>
  6. <first-name>Margaret</first-name>
  7. <last-name>Atwood</last-name>
  8. </author>
  9. <price>19.95</price>
  10. </book>
  11. <book genre="novel" style="other">
  12. <title>The Poisonwood Bible</title>
  13. <author>
  14. <first-name>Barbara</first-name>
  15. <last-name>Kingsolver</last-name>
  16. </author>
  17. <price>11.99</price>
  18. </book>
  19. </bookstore>

C#代码

  1. using System;
  2. using System.IO;
  3. using System.Xml;
  4.  
  5. public class Sample
  6. {
  7. public static void Main()
  8. {
  9.  
  10. XmlDocument doc = new XmlDocument();
  11. doc.Load("newbooks.xml");
  12.  
  13. // Create an XmlNamespaceManager to resolve the default namespace.
  14. XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NaMetable);
  15. nsmgr.AddNamespace("bk","urn:newbooks-schema");
  16.  
  17. // Select the first book written by an author whose last name is Atwood.
  18. XmlNode book;
  19. XmlElement root = doc.DocumentElement;
  20. book = root.SelectSingleNode("descendant::bk:book[bk:author/bk:last-name='Atwood']",nsmgr);
  21.  
  22. Console.WriteLine(book.OuterXml);
  23.  
  24. }
  25. }

猜你在找的XML相关文章