选择节点与几个命名空间值的XML文档返回任何内容 [英] Selecting node with several namespaces values in XML document returns nothing

查看:230
本文介绍了选择节点与几个命名空间值的XML文档返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有类似的XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<Data Version="3" xsi:schemaLocation="uuid:ebfd9-45-48-a9eb-42d Data.xsd" xmlns="uuid:ebfd9-45-48-a9eb-42d" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Info>
    <Muc>Demo</Muc>
  </Info>
</Data>



我做的。

I am doing

Dim m_xmld As XmlDocument
m_xmld = New XmlDocument()
m_xmld.Load("myXML.xml")
Dim test As XmlNode
test = doc.SelectSingleNode("Data/Info", GetNameSpaceManager(m_xmld))

有:

 Public Shared Function GetNameSpaceManager(ByRef xDoc As XmlDocument) As XmlNamespaceManager
        Dim nsm As New XmlNamespaceManager(xDoc.NameTable)
        Dim RootNode As XPathNavigator = xDoc.CreateNavigator()
        RootNode.MoveToFollowing(XPathNodeType.Element)
        Dim NameSpaces As IDictionary(Of String, String) = RootNode.GetNamespacesInScope(XmlNamespaceScope.All)
        For Each kvp As KeyValuePair(Of String, String) In NameSpaces
            nsm.AddNamespace(kvp.Key, kvp.Value)
        Next
        Return nsm
    End Function

不过,我不断获取无读取XML时。有没有办法忽略的命名空间?问题是,一些命名空间的文件可能有所不同,这就是为什么我添加 GetNameSpaceManager 函数...

However I keep on getting "Nothing" when reading the xml. Is there a way to ignore the namespaces?. The issue is that some namespaces may vary between files, thats why I added GetNameSpaceManager function...

推荐答案

在XPath中,没有前缀的元素名称空空间始终被认为。在XML中,虽然,有的默认命名空间的哪些元素隐含在默认情况下继承,这一个在特定的XML:

In XPath, element name without prefix is always considered in empty namespace. In XML though, there is default namespace which elements implicitly inherits by default, this one in your particular XML :

xmlns="uuid:ebfd9-45-48-a9eb-42d"

我想建议使用默认的前缀,比如 D ,在你的XPath。然后映射的前缀根元素的命名空间:

I'd suggest to use a default prefix, say d, in your XPath. And then map the prefix to the root element's namespace :

......
Dim nsManager As New XmlNamespaceManager(New NameTable())
nsManager.AddNamespace("d", m_xmld.DocumentElement.NamespaceURI)
test = doc.SelectSingleNode("d:Data/d:Info", nsManager)

上面将上这两种情况下工作(XML文档具有和不具有默认名称空间),但不是在情况下的与默认XML在命名空间后代元素级别本地声明。

The above will work on both cases (XML document with and without default namespace), but not in case an XML with default namespace declared locally at the descendant elements level.

这篇关于选择节点与几个命名空间值的XML文档返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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