0

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?

2
  • Perhaps: oXPathNameNavigator.SelectSingleNode("name").Value is equal to null? Commented Dec 23, 2013 at 16:02
  • Yes, it is null but I don't know why. In xml tag "name" has value "ABORG", so how can I change my code to obtain that value? Commented Dec 23, 2013 at 16:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.