1

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);

1 Answer 1

2

Use list = doc.SelectNodes("//a:span[@class='distinct']/a:img", nsmgr); and you will get back the img node.

Some explanation in this answer

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

1 Comment

This works, thanks. So this is just an xpath issue, not even asp.net. Namespace prefix is not 'inherited' like a default namespace would be - for whatever reason I was expecting that.

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.