本文介绍了解析 MSXML 时引用未声明的命名空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何解决

Reference to undeclared namespace prefix: '%s'

Microsoft 的 msxml 实现有问题吗?

problem with Microsoft's msxml implementation?

我正在使用来自政府网站的 XML 提要,其中包含我需要解析的值.xml 包含命名空间:

I'm using an XML feed from a government web-site that contains values i need to parse. The xml contains namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/"
    xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3c.org/1999/02/22-rdf-syntax-ns#rdf.xsd">
    <item rdf:about="http://www.bankofcanada.ca/stats/rates_rss/STATIC_IEXE0101.xml">
        <cb:statistics>
            <cb:exchangeRate>
                <cb:value decimals="4">1.0351</cb:value>
                <cb:baseCurrency>CAD</cb:baseCurrency>
                <cb:targetCurrency>USD</cb:targetCurrency>
                <cb:rateType>Bank of Canada noon rate</cb:rateType>
                <cb:observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</cb:observationPeriod>
            </cb:exchangeRate>
        </cb:statistics>
    </item>
</rdf:RDF>

运行 XPath 查询:

Running the XPath query:

/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency

因错误而失败:

Reference to undeclared namespace prefix: 'rdf'

编辑:

如果我编辑原始 XML 以删除所有命名空间的使用:

If i edit the original XML to remove all use of namespaces:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rdf>
    <item>
        <statistics>
            <exchangeRate>
                <value decimals="4">1.0351</value>
                <baseCurrency>CAD</baseCurrency>
                <targetCurrency>USD</targetCurrency>
                <rateType>Bank of Canada noon rate</rateType>
                <observationPeriod frequency="daily">2011-05-09T12:15:00-04:00</observationPeriod>
            </exchangeRate>
        </statistics>
    </item>
</rdf>

查询/rdf/item/statistics/exchangeRate/baseCurrency 没有失败,并返回节点:

The query /rdf/item/statistics/exchangeRate/baseCurrency doesn't fail, and returns nodes:

<baseCurrency>CAD</baseCurrency>

如何让 Microsoft XML 使用命名空间?

How do i get Microsoft XML to work with namespaces?

我尝试将 SelectionNamespaces 添加到 DOMDocument 对象:

i've tried adding SelectionNamespaces to the DOMDocument object:

doc.setProperty('SelectionNamespaces', 'xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cb="http://www.cbwiki.net/wiki/index.php/Specification_1.1"');

现在 xpath 查询不会失败,但它也不会返回任何节点:

Now the xpath query doesn't fail, but it also returns no nodes:

nodes = doc.selectNodes('/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency');

另见