0

i am trying to create an application which would output the data present at some xpath(which will be specified by user)

XPathDocument xmldoc = new XPathDocument(file);
XPathNavigator nav = xmldoc.CreateNavigator();
XPathNavigator result = nav.SelectSingleNode("//p");
MessageBox.Show(result.Value);

Here variable file is location of xml file. Now when I am running this code on a xml file that has lots of namespaces defined on it , the above code returns nullreference exception, because variable result is null and i am trying to access
result.Value .

But when i created my own xml file

<a>
<b>
<p>abc</p> 
</b>
</a>

the codes runs fine .

So, what i am inferring is that the problem is because i am not including the namespaces in the code.

I searched and found out the suggestion that the way to trick namespaces is to use relative xpaths such as //p .Here What is a good way to find a specific value in an XML document using C#?

But the code still does not works on the original file (one containing the namespaces)

Community
  • 1
  • 1
anurag
  • 137
  • 2
  • 11

1 Answers1

1

How about:

XPathNavigator result = nav.SelectSingleNode("//*[local-name()='p']");
jlew
  • 10,491
  • 1
  • 35
  • 58
  • Yes it worked . So do i need to use local-name whenever i want to avoid namespaces ? – anurag Jan 14 '14 at 13:33
  • You are essentially doing a string compare. local-name() returns the element name without the namespace, so if that's what you need, use it. However, make sure there is no possibility that an element with the same name might exist in a different namespace in your document, causing unwanted selection. – jlew Jan 14 '14 at 15:37