I have an XmlDocument with namespaces, I need to find a specific child of an element with a specific attribute. I can get the parent, and I can get all the children, but I can't find an xpath expression to just get element (img) I want. I could go through the children and just find img elements, but I'd really like to find it with just one xpath expression.
The first SelectNodes gives me all children of the span with class='distinct'. I want only the img element. The second select returns 0 nodes.
If the namespace is not present in the expression or the xml, the second select will return the img element.
XML:
<p xmlns="blorf">
<span class="distinct" >
<img alt="" src="eq_54.png"/>
<span class="other-span">
<inner xmlns="scrubs">
<x1/>
</inner>
</span>
</span>
</p>
Code:
...
doc.LoadXml(_xml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("a", "blorf");
XmlNodeList list = doc.SelectNodes("//a:span[@class='distinct']/*",nsmgr);
Console.WriteLine("count is " + list.Count);
list = doc.SelectNodes("//a:span[@class='distinct']/img", nsmgr);
Console.WriteLine("count is " + list.Count);
Use list = doc.SelectNodes("//a:span[@class='distinct']/a:img", nsmgr);
and you will get back the img
node.
Some explanation in this answer