C# 解析xml文件(带命名空间 xmlns和 xmlns:xsi)

 1、带有命名空间 并且命名空间后带 xmlns:xsi =" "

 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>

解析:

 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             }

 

2、带有命名空间 不带前缀 xmlns=" "

 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>

解析:

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

 

C# 解析xml文件(带命名空间 xmlns和 xmlns:xsi)

上一篇:C#设计模式:备忘录模式(Memento Pattern)


下一篇:解决Adobe cs6系列软件在Windows10操作系统中无法正常运行问题