0

I have to get certain nodes(their InnerText) from xml file. I know their names, but nodes might be using some namespaces which i don't know. Is it possible to get node using SelectSingleNode() or some other method without knowing the namespace the node is using? Is it possible to ignore namespaces the nodes are using?

2 Answers 2

3

Use namespace-agnostic XPath. Not particularly nice or efficient, but it works.

Instead of this:

/ns1:foo/ns2:bar/ns3:baz

use this:

/*[local-name() = 'foo']/*[local-name() = 'bar']/*[local-name() = 'baz']

Be prepared to face the consequences of losing namespaces:

<ns1:foo>
  <wrong:bar>
    <wrong:baz />    <!-- this would be selected (false positive) -->
  </wrong:bar>
  <ns2:bar>
    <ns3:baz />
  </ns2:bar>
</ns1:foo>
Sign up to request clarification or add additional context in comments.

Comments

0
XmlDocument doc = new XmlDocument();
doc.Load("foo.xml");

XmlElement b, f1, f2;

b =  (XmlElement)doc.SelectSingleNode("//bar");
f1 = (XmlElement)b.SelectSingleNode("ancestor::foo[1]");
f2 = (XmlElement)b.SelectNodes("ancestor::foo")[0];

Console.WriteLine(f1.GetAttribute("depth"));
Console.WriteLine(f2.GetAttribute("depth"));

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.