当文档没有命名空间时,我应该为 XmlDocument.SelectSingleNode 使用哪个 XPath 表达式? [英] Which XPath expression should I use for XmlDocument.SelectSingleNode when the document has no namespace?

查看:24
本文介绍了当文档没有命名空间时,我应该为 XmlDocument.SelectSingleNode 使用哪个 XPath 表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些通过 JSON 响应流的默认转换生成的 XML,因此没有声明命名空间.我现在想使用 SelectSingleNode 方法从该 XML 中检索特定节点,但无法指定命名空间,因为没有指定命名空间.我应该使用什么来注册命名空间?

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?

我的 XML 如下所示:

My XML looks like this:

<root type="object">
  <customer type="object">
    <firstName type="string">Kirsten</firstName>
    <lastName type="string">Stormhammer</lastName>
  </customer>
</root>

我试过的代码是:

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

这总是返回 null.

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

这也返回 null.

推荐答案

那么你就可以用更简单的方式来做,无需涉及XmlNamespaceManager 和命名空间前缀:

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 小提琴演示]

这篇关于当文档没有命名空间时,我应该为 XmlDocument.SelectSingleNode 使用哪个 XPath 表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆