【发布时间】:2016-02-23 08:59:31
【问题描述】:
我想在 MS Access 中使用 VBA 来读取某些 XML,但在解析此 XML 时出现“对象变量或未设置块引用”错误...
<?xml version="1.0"?>
<GetCompetitivePricingForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetCompetitivePricingForASINResult ASIN="B002L7HJAA" status="Success">
<Product
xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01"
xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>A1F83G8C2ARO7P</MarketplaceId>
<ASIN>B002L7HJAA</ASIN>
</MarketplaceASIN>
</Identifiers>
<CompetitivePricing>
<CompetitivePrices>
<CompetitivePrice belongsToRequester="false" condition="New" subcondition="New">
<CompetitivePriceId>1</CompetitivePriceId>
<Price>
<LandedPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>14.45</Amount>
</LandedPrice>
</Price>
</CompetitivePrice>
</CompetitivePrices>
</CompetitivePricing>
</Product>
</GetCompetitivePricingForASINResult>
</GetCompetitivePricingForASINResponse>
使用此代码...
Public Function READXML()
Dim objXMLNode1 As MSXML2.IXMLDOMNodeList
Set objXMLDoc = New MSXML2.DOMDocument60
objXMLDoc.loadXML ("C:\Users\LW\Desktop\formatted.xml")
XmlNamespaces = "xmlns:ns2='http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd' xmlns:ns1='http://mws.amazonservices.com/schema/Products/2011-10-01'"
objXMLDoc.SetProperty "SelectionNamespaces", XmlNamespaces
Set objXMLNode1 = objXMLDoc.selectSingleNode("//ns2:Price/ns2:LandedPrice/ns2:Amount")
MsgBox objXMLNode1(0).text
End Function
如您所见,我试图提取 XML 值(在 XML 中显示为 14.45)
我在谷歌上搜索了很长时间都无济于事,但是在阅读了'SelectSingleNode' XPath query from XML with multiple Namespaces之后,我选择了上面的代码
任何想法为什么我会收到错误?
【问题讨论】:
-
哪一行出现错误?
XmlNamespaces是什么?它没有被宣布。尝试使用Option Explicit并在声明所有变量并修复所有拼写错误后编辑您的问题。 -
您好 John,是 MsgBox objXMLNode1(0).text 行给出了错误。重新声明 XMLNameSpace ...好点!
-
@peskywinnets 您使用了错误的前缀。改用
//ns1:Price/ns1:LandedPrice/ns1:Amount试试... -
谢谢,但更改为 //ns1:Price/ns1:LandedPrice/ns1:Amount 仍然会导致相同的错误。