在 VBA 中解析 XML 响应数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16840275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing XML response data in VBA
提问by Andre Josephs
I am calling the stockquote webservice and trying to parse through the data that is returned but nothing I try is working
我正在调用股票报价网络服务并尝试解析返回的数据,但我尝试的任何内容都不起作用
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
objHTTP.Open "GET", "http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=AAPL", False
objHTTP.send
Dim xDoc As MSXML2.DOMDocument
Dim xDoc2 As MSXML2.IXMLDOMNodeList
Set xDoc = New MSXML2.DOMDocument
xDoc.LoadXML (objHTTP.responseXML.XML)
I know everything works up to this point and I can look at the Xdoc object in the debugger and see that the xml was loaded.
我知道到目前为止一切正常,我可以在调试器中查看 Xdoc 对象并查看 xml 是否已加载。
How do I access the individual nodes after this?
the sample xml looks like this
"<string xmlns="http://www.webserviceX.NET/"><StockQuotes><Stock><Symbol>AAPL</Symbol><Last>446.5345</Last>
<Date>5/30/2013</Date><Time>10:55am</Time><Change>+1.5845</Change></Stock></StockQuotes></string>"
在此之后如何访问各个节点?示例 xml 看起来像这样
"<string xmlns="http://www.webserviceX.NET/"><StockQuotes><Stock><Symbol>AAPL</Symbol><Last>446.5345</Last>
<Date>5/30/2013</Date><Time>10:55am</Time><Change>+1.5845</Change></Stock></StockQuotes></string>"
回答by Martin Honnen
It seems the response is an XML document with a single root element containing an escaped XML document:
似乎响应是一个 XML 文档,其中包含一个包含转义 XML 文档的单个根元素:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.webserviceX.NET/"><StockQuotes><Stock><Symbol>AAPL</Symbol><Last>448.9501</Last><Date>5/30/2013</Date><Time>12:17pm</Time><Change>+4.0001</Change><Open>445.65</Open><High>449.77</High><Low>444.51</Low><Volume>5691335</Volume><MktCap>421.4B</MktCap><PreviousClose>444.95</PreviousClose><PercentageChange>+0.90%</PercentageChange><AnnRange>385.10 - 705.07</AnnRange><Earns>41.896</Earns><P-E>10.62</P-E><Name>Apple Inc.</Name></Stock></StockQuotes></string>
So you need to load the first document and then access its content and parse it as XML with a second document:
因此,您需要加载第一个文档,然后访问其内容并将其解析为带有第二个文档的 XML:
Dim doc1 As MSXML2.DOMDocument60
Set doc1 = New MSXML2.DOMDocument60
doc1.async = False
If doc1.load("http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=AAPL") Then
Dim doc2 As MSXML2.DOMDocument60
Set doc2 = New MSXML2.DOMDocument60
If doc2.loadXML(doc1.DocumentElement.text) Then
Dim value
value = doc2.selectSingleNode("//Last").text
Else
'handle doc2.parseError here
End If
Else
' handle doc1.parseError her
End If
Untested but should give you an idea.
未经测试,但应该给你一个想法。