【问题标题】:What is the prefix of an XML document which does not have a prefix defined?没有定义前缀的 XML 文档的前缀是什么?
【发布时间】:2012-12-11 18:31:52
【问题描述】:

更新 感谢 florent,我现在意识到我在问题中使用了错误的术语(最初是:'什么是未定义命名空间的 XML 文档的命名空间?')。
另外,我想现在我要问两个问题:
1. 可以为没有前缀的 XML 文档分配前缀吗? (可能是的,但是如何使用经典 ASP 做到这一点?)
2. XML 文档中没有定义前缀的节点的 XPath 位置路径是什么?如果这是可能的。


我有经典的 ASP 代码,它使用 MSXML2.ServerXMLHTTP.6.0 对象检索 XML 文档,但 XML 文档没有定义前缀。我无法更改 XML 文档的制作方式。

这就是 XML 的外观:

<?xml version="1.0" standalone="yes"?>
<SearchResultsResponse xmlns="http://openapi.somesite.com/openapi-3.0.0">
[...]
</SearchResultsResponse>    


该文档会通过 .responseXML 属性自动解析和访问。但查找节点:

Set objData = obj_http.responseXML.selectSingleNode("//someNodeName")
Response.Write "Data: " & objData.Text

不起作用。 (我收到“需要对象”错误消息,表示未找到节点。)并且

Response.Write obj_http.responseXML.documentElement.prefix 

给我一​​个空字符串。


完成这项工作的一种方法是使用.selectSingleNode("//*[local-name() = 'someNodeName']"),但我想这在较大的 XML 文档中效率不高。 (或者我错了吗?)

我读过类似:.selectSingleNode("//ns:rootNodeName/ns:childNodeName"),其中“ns”是定义的前缀,应该是要走的路,但是如果没有定义前缀,我应该使用什么前缀?

【问题讨论】:

    标签: xml namespaces msxml serverxmlhttp


    【解决方案1】:

    据我了解,“http://openapi.somesite.com/openapi-3.0.0”是文档的命名空间。它只是没有定义前缀,所以这是默认命名空间。

    我读过类似的内容: .selectSingleNode("//ns:rootNodeName/ns:childNodeName"),其中'ns'是 定义的命名空间,应该是要走的路,但是我应该怎么做 如果没有定义,则用于命名空间?

    "ns" 这里不是命名空间而是命名空间前缀。我不是 ASP 人员,所以我对代码帮助不大,但您仍然应该能够为您的节点查找定义命名空间。如果您不想使用默认命名空间,您甚至应该能够使用前缀重新定义它。

    【讨论】:

    • 你是绝对正确的。作为 XML 新手,我使用了错误的术语。我会更新我的问题。
    • 我对 msxml 不熟悉,所以对于特殊情况我不能多说。但是您始终可以在解析器中(例如在 xslt 中)重新定义前缀,然后在 xpath 中使用此前缀。
    • 看这里:social.msdn.microsoft.com/Forums/is/xmlandnetfx/thread/… 你应该能够使用属性重新定义命名空间:objResponse.responseXML.setProperty("SelectionNamespaces", "xmlns:myns='openapi.somesite.com/openapi-3.0.0'") objResponse.responseXML。 selectSingleNode("//someNodeName")
    【解决方案2】:

    我终于明白了:

    Dim obj_XML
    Set obj_XML = obj_http.responseXML
    
    ' this is where the magic happens, 'ns' is defined as the prefix:
    obj_XML.setProperty _
        "SelectionNamespaces", _
        "xmlns:ns='http://openapi.somesite.com/openapi-3.0.0' " &_
        "xmlns:xs='http://www.w3.org/2001/XMLSchema'"
    
    Dim obj_node
    ' now we can get the node with an XPath location path with the 'ns' prefix:
    Set obj_node = obj_XML.selectSingleNode("//ns:SearchResultsResponse/ns:SessionId")
    
    If obj_node Is Nothing Then
        Response.Write "# No node found #<br />"
    Else
        Response.Write "Node text: " & obj_node.Text & "<br />"
    End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多