xml - 为什么在解析 XML 时需要 XmlNamespaceManager

标签 xml vb.net visual-studio-2010

因此,当我使用 selectSingleNode 获取空值时,我发现我需要声明一个 namespace ,因为我正在使用 xmlns 属性。我的问题是,如果我不在 xml 文件本身中使用前缀,为什么在解析 xml 时需要使用前缀?

我之所以拥有 xmlns 属性,是因为我的 xml 输出的接收端需要它。我宁愿从基本 xml 中读取它,也不愿在程序中对其进行硬编码。

这是有效的代码

xmlns = New XmlNamespaceManager(xmlTemplate.NameTable)
xmlns.AddNamespace("dc", ns)

我试过这样做 - 不起作用

xmlns = New XmlNamespaceManager(xmlTemplate.NameTable)
xmlns.AddNamespace(String.Empty, ns)

简而言之,有什么办法去掉“dc”前缀吗?

最佳答案

这只是“这就是他们构建它的方式”之类的事情之一。根据MSDN (XPath Queries with Namespaced Mapped Prefixes) :

The XmlNamespaceManager allows adding default namespaces by using an empty string as the prefix. However, XPath treats the empty prefix as the null namespace. In other words, only prefixes mapped to namespaces can be used in XPath queries. If you want to use the default namespace from an XML document in the XPath expression, then you need to define a prefix for it.

还有来自 MSDN (XmlNamespaceManager.AddNamespace) :

If the XmlNamespaceManager will be used for resolving namespaces in an XML Path Language (XPath) expression, a prefix must be specified. If an XPath expression does not include a prefix, it is assumed that the namespace Uniform Resource Identifier (URI) is the empty namespace

编辑

我假设你的代码是这样的:

Dim S = "<xml xmlns=""http://www.exmaple.com/""><node/></xml>"

Dim X As New Xml.XmlDocument()

X.LoadXml(S)
Dim NS As New Xml.XmlNamespaceManager(X.NameTable)
NS.AddNamespace("dc", "http://www.exmaple.com/")

''//Will not work
Dim N1 = X.SelectSingleNode("//xml/node", NS)
If N1 Is Nothing Then
    Trace.WriteLine("Node not found")
Else
    Trace.WriteLine("Node found")
End If

''//Works
Dim N2 = X.SelectSingleNode("//dc:xml/dc:node", NS)
If N2 Is Nothing Then
    Trace.WriteLine("Node not found")
Else
    Trace.WriteLine("Node found")
End If

关于xml - 为什么在解析 XML 时需要 XmlNamespaceManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5421875/

相关文章:

javascript - 如何在 Iframe 中显示 aspx 站点

c# - 将项目添加到 Visual Studio 解决方案时出现的问题

java - XMLEventWriter 不写入输出流

xml - 如何使用 XSLT 从 XML 中删除某些属性

python - 从url列表中提取html代码

c++ - 为什么我的内联汇编程序不能按预期工作?

c++ - 某些配置 VS 2010 中的特定项目缺少符号

javascript - 使用Firefox XML DOM解析XML(RSS)

javascript - 如何获取 Nativescript 中复选框的值?

javascript - 如何注释掉混有服务器标签的一段 javascript 代码