简体   繁体   中英

How to add namespace to XPath in C#?

I tried to parse an XML file: http://www.ikea.com/pl/pl/catalog/products/30198858?type=xml&dataset=normal,parentCategories,allImages but I obtained error

Namespace Manager or XlstContext needed. This query has a prefix, variable or user-definde function."

Code:

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;

I found that this error is being caused by lack of namespace so I tried to add it like this:

XmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);
nameSpace.AddNamespace("ir",path);

Now I have new error:"System.NullReferenceException: Object reference not set to an instance of an object." in line:

productModel.productName = oXPathNameNavigator.SelectSingleNode("name").Value;

What's wrong with my code?

Namespace handling always trips me up, so I had to play around for a bit to get this working right. Your big problem was that when you add a namespace, you provide the address for that namespace, not reuse the path to the xml doc itself.

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;

I tested this in LinqPAD and I was able to correctly get at the node you were interested in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM