【问题标题】:XML nodes with root not working in VBScript带有根的 XML 节点在 VBScript 中不起作用
【发布时间】:2015-03-31 20:29:02
【问题描述】:

以下代码适用于 XML 1,但不能从 XML 2 读取行(添加了 ROOT)。你知道为什么吗?

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.async="false"
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("test.xml")

set  nodes=xmlDoc.SelectNodes("//customer")
for i=0 to nodes.length-1
set node = nodes(i)
set company = node.selectSingleNode("company")
msgbox company
next

XML 1:

<?xml version="1.0" encoding="UTF-8"?>
<customers>
    <customer>
        <name>ABCars</firma>
    </customer>
</customers>

XML 2:

<?xml version="1.0" encoding="UTF-8"?>
<ROOT xmlns="http://www.something.com ">
    <customers>
        <customer>
            <name>ABCars</firma>
        </customer>
    </customers>
</ROOT>

【问题讨论】:

    标签: xml vbscript


    【解决方案1】:

    这是因为您的第二个文档具有默认命名空间。 XPath 使用默认名称空间很时髦。您需要添加一个命名空间前缀(例如xmlns:ns0="http://www.something.com",然后使用该前缀(ns0:ROOTns0:customers 等),或者重构您的 XPath 以使用 local-name() 函数:

    set nodes=xmlDoc.SelectNodes("//*[local-name()='customer']")
    

    您还必须更改您的 selectSingleNode:

    set company = node.selectsingleNode("*[local-name()='company']")
    

    如果您在此站点中搜索“XPath 默认命名空间”,您会发现很多相关问题。

    【讨论】:

    • 非常感谢!还有一件事 - 如果我使用语法: set nodes=xmlDoc.SelectNodes("//*[local-name(.) = 'customer']") 我怎样才能获得客户名称值? set company = node.selectSingleNode("name") 似乎不再起作用了。
    • 我已经更新了答案。如果这回答了您的问题,请考虑通过单击其下方的复选框将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多