问题
I have some XML that has been generated by default conversion of a JSON response stream, and so doesn't have a namespace declared. I now want to retrieve a specific node from that XML by using the SelectSingleNode method, but cannot specify the namespace because there isn't one specified. What should I use to register a namespace?
My XML looks like this:
<root type="object">
<customer type="object">
<firstName type="string">Kirsten</firstName>
<lastName type="string">Stormhammer</lastName>
</customer>
</root>
The code I have tried is:
XmlDocument document = new XmlDocument();
document.LoadXml(customerXml);
XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
manager.AddNamespace("x", "http://www.w3.org/TR/html4/"); // What should I use here?
XmlNode customerNode= document.SelectSingleNode("x:customer");
This always returns null.
I have also tried using the local-name qualifier (without using a namespace manager):
XmlDocument document = new XmlDocument();
document.LoadXml(customerXml);
XmlNode customerNode= document.SelectSingleNode("/*[local-name()='root']/*[local-name()='customer']");
This also returns null.
回答1:
Then you can do in a much simpler way, without involving XmlNamespaceManager
and namespace prefix :
XmlDocument document = new XmlDocument();
document.LoadXml(customerXml);
XmlNode customerNode= document.SelectSingleNode("/root/customer");
[.NET fiddle demo]
来源:https://stackoverflow.com/questions/26215177/which-xpath-expression-should-i-use-for-xmldocument-selectsinglenode-when-the-do