Which XPath expression should I use for XmlDocument.SelectSingleNode when the document has no namespace?

社会主义新天地 提交于 2021-01-29 18:12:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!