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 names开发者_开发问答paces the nodes are using?
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>
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"));
精彩评论