我如何解决
- Reference to undeclared namespace prefix: '%s'
微软msxml实现的问题?
我正在使用来自政府网站的XML Feed,其中包含我需要解析的值. xml包含命名空间:
- <?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查询:
- /rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency
- Reference to undeclared namespace prefix: 'rdf'
编辑:
如果我编辑原始XML以删除所有使用命名空间:
- <?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不会失败,并返回节点:
- <baseCurrency>CAD</baseCurrency>
如何让Microsoft XML使用命名空间?
编辑2
我已经尝试添加SelectionNamespaces到DOMDocument对象:
现在,xpath查询不会失败,但它也不返回任何节点:
- nodes = doc.selectNodes('/rdf:RDF/item/cb:statistics/cb:exchangeRate/cb:targetCurrency');
也可以看看
> “undeclared reference to namespace prefix ” error
> XMLReader – How to handle undeclared namespace
> PRB: Specifying Fully Qualified Element Names in XPath Queries
> XPath not working properly.
使用SelectionNamespaces是正确的方法,你只是缺少一个命名空间.
请注意,您的XML文档显式设置默认命名空间如下:
- xmlns="http://purl.org/RSS/1.0/"
这意味着任何没有前缀的元素(如item元素)实际上都在默认的命名空间中.因此,如果要使用XPath表达式选择该元素,则必须首先设置适当的选择命名空间.
为此,您可以将您的来电更改为setProperty,如下所示:
在这里,您将默认名称空间从文档分配给XPath表达式中的RSS:前缀.随着这种改变,以下XPath表达式应该正常工作:
- nodes = doc.selectNodes('/rdf:RDF/RSS:item/cb:statistics/cb:exchangeRate/cb:targetCurrency');
它的作用是因为它使用正确的命名空间引用了item元素. XPath表达式和原始文档之间前缀不同的事实是无关紧要的.它是前缀绑定到的重要名称空间.