我试图解析一个 XML 文件:http://www.ikea.com/pl/pl/catalog/products/30198858?type=xml&dataset=normal,parentCategories,allImages但我得到了错误
Namespace Manager or XlstContext needed. This query has a prefix, variable or user-definde function."
代码:
XPathDocument oXPathDocument = new XPathDocument(path);
XPathNavigator oXPathNameNavigator = oXPathDocument.CreateNavigator();
XPathNodeIterator oProductNodesIterator = oXPathNameNavigator.Select(@"/ikea-rest/products/product/items/item");
productModel.productName = oXPathNameNavigator.SelectSingleNode("name").Value;
我发现这个错误是由缺少命名空间引起的,所以我尝试像这样添加它:
XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);
nameSpace.AddNamespace("ir",path);
现在我有新错误:“System.NullReferenceException:未将对象引用设置为对象的实例。”排队:
productModel.productName = oXPathNameNavigator.SelectSingleNode("name").Value;
我的代码有什么问题?
最佳答案
命名空间处理总是让我绊倒,所以我不得不玩一会儿才能让它正常工作。你的大问题是,当你添加一个命名空间时,你提供了该命名空间的地址,而不是重用 xml 文档本身的路径。
XPathDocument oXPathDocument = new XPathDocument(path);
XPathNavigator oXPathNameNavigator = oXPathDocument.CreateNavigator();
XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);
//use the namespace address provided in the XML, not the path to the xml itself
nameSpace.AddNamespace("ir","http://www.ikea.com/v1.0");
//now you have to scope your query to the namespace you just defined, otherwise xpath will assume the node is not in a namespace
productModel.productName = oXPathNameNavigator.SelectSingleNode("//ir:ikea-rest/products/product/name", nameSpace).Value;
我在 LinqPAD 中对此进行了测试,并且能够正确到达您感兴趣的节点。
关于c# - 如何在 C# 中为 XPath 添加命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746944/