Question : Xpath query with namespace(s)

Hi experts,

Let's assume that the XML at the beginning of the code is loaded in C# in XmlDocument d.

I want to select the <c>value</c> node using d.SelectNodes(). I've tried the calls in the code but none of them succeeded. What should be the right code to get the requested node?
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
// xml
<root>
<a>
<b xmlns="namespace">
<c>value</c>
</b>
</a>
</root>

// code 1
d.SelectNodes("/root/a/b/c");

// code 2
XmlNamespaceManager xnsmgr = new XmlNamespaceManager(d);
xnsmgr.AddNamespace(String.Empty, "namespace");
d.SelectNodes("/root/a/b/c", xnsmgr); // xnsmgr is XmlNamespaceManager 

// code 3
XmlNamespaceManager xnsmgr = new XmlNamespaceManager(d);
xnsmgr.AddNamespace("a", "namespace"); // the prefix mustn't be empty according to MSDN
xnsmgr.AddNamespace("a", "");
d.SelectNodes("/root/a/b/c", xnsmgr); // xnsmgr is XmlNamespaceManager

Answer : Xpath query with namespace(s)

You are going to have to use a namespace prefix because you have two different namespaces in your document:

1:
2:
3:
4:
XmlNamespaceManager xnsmgr = new XmlNamespaceManager(d);
xnsmgr.AddNamespace("x", "namespace");

d.SelectNodes("/root/a/x:b/x:c", xnsmgr);
Random Solutions  
 
programming4us programming4us