bruno
bruno

Reputation: 33

Getting single node without knowing its namespace

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?

Upvotes: 0

Views: 873

Answers (2)

user384929
user384929

Reputation:

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

Upvotes: 0

Tomalak
Tomalak

Reputation: 338386

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>

Upvotes: 3

Related Questions