【发布时间】:2017-06-12 13:59:45
【问题描述】:
我有类似这样的 XML 代码:
<BookStore xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Book>
<bookGenre>Fantasy</bookGenre>
<bookTitle>A Storm of Swords</bookTitle>
<authorInformation>
<authorId>12345</authorId>
<authorName>
<firstName>George</firstName>
<middleInitial>R.R.</middleInitial>
<lastName>Martin</lastName>
</authorName>
</authorInformation>
</Book>
<customer>
<customerData />
</customer>
</BookStore>
<customer>node 可能有也可能没有子节点,具体取决于用户输入。
我正在尝试使用 XmlDocument.SelectNodes 和 XPath 导航来选择 <BookStore>、<customer> 以及 <customer> 中包含的任何节点。
几个小时以来,我一直在四处寻找和阅读有关 XPath 和 .SelectNodes 的信息,但似乎仍然没有完全理解它们是如何工作的。有人可以解释如何使用它们或我如何在我的情况下使用它们吗?如果还有其他方法可以解决我的问题,我也愿意接受! (我使用的是 C#)
编辑:这是我根据阅读的内容尝试过的内容
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
XmlNode root = doc.DocumentElement;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
XmlNodeList nodeList = root.SelectNodes("descendant::customer:child::Node");
doc.Save(Console.Out);
【问题讨论】:
-
请向我们展示您的尝试。
-
添加了我试过的代码。
-
那么当你调用
doc.LoadXml()并给它一个文件名而不是一个XML 字符串时会发生什么?我知道会发生什么。我在问你为什么在你尝试解析 XML 时没有在你的问题中说任何关于获取异常的内容。 -
使用 LINQ to XML 应该是
var customerData = XDocument.Load(fileName).Descendants("customerData"); -
哦,对不起,这让我很困惑,我曾经使用一个文件,但后来我只是将 fileName 更改为接收 XML 字符串而不更改变量名,我将对其进行编辑:P
标签: c# xml xpath selectnodes