先上xml
<?xml version="1.0" encoding="utf-8" ?> <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"> <PayCount>1</PayCount> <BlackWords /> <ErrorMobiles /> <BlackMobiles /> <BatchSendID>00000000-0000-0000-0000-000000000000</BatchSendID> <Result>aaa</Result> <ErrorDesc>成功</ErrorDesc> </SendExResp>
需要注意,xmlns后面跟:**与不跟,读取时是不同的,看后台代码
String path = System.AppDomain.CurrentDomain.BaseDirectory + "//return.xml"; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(path); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmldoc.NaMetable); //namespace namespaceManager.AddNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance"); namespaceManager.AddNamespace("xsd","http://www.w3.org/2001/XMLSchema"); namespaceManager.AddNamespace("d","urn:schemas-microsoft-com:office:spreadsheet"); XmlNode node = xmldoc.SelectSingleNode("descendant::d:Result",namespaceManager); if (node != null) { string s = node.InnerText; }如果命 名空间都是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.
<?xml version='1.0'?> <bookstore xmlns="urn:newbooks-schema"> <book genre="novel" style="hardcover"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>19.95</price> </book> <book genre="novel" style="other"> <title>The Poisonwood Bible</title> <author> <first-name>Barbara</first-name> <last-name>Kingsolver</last-name> </author> <price>11.99</price> </book> </bookstore>
C#代码:
using System; using System.IO; using System.Xml; public class Sample { public static void Main() { XmlDocument doc = new XmlDocument(); doc.Load("newbooks.xml"); // Create an XmlNamespaceManager to resolve the default namespace. XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NaMetable); nsmgr.AddNamespace("bk","urn:newbooks-schema"); // Select the first book written by an author whose last name is Atwood. XmlNode book; XmlElement root = doc.DocumentElement; book = root.SelectSingleNode("descendant::bk:book[bk:author/bk:last-name='Atwood']",nsmgr); Console.WriteLine(book.OuterXml); } }原文链接:https://www.f2er.com/xml/300200.html