我正在尝试自学VBA和XML的基础知识来解决我在Excel中正在处理的特定问题。我正在尝试使用API来获取给定lat / lon的人口普查区块ID。
这是XML代码:
<Response xmlns="http://data.fcc.gov/api" status="OK" executionTime="120">
<Block FIPS="120950170151016">
<intersection FIPS="120950170151016"></intersection>
<intersection FIPS="120950170151019"></intersection>
<intersection FIPS="120950170151015"></intersection>
</Block>
<County FIPS="12095" name="Orange"></County>
<State FIPS="12" code="FL" name="Florida"></State>
<messages>FCC0001: The coordinate lies on the boundary of mulitple blocks, first FIPS is displayed. For a complete list use showall=true to display 'intersection' element in the Block</messages>
<head></head>
</Response>
我可以开始工作的唯一VBA命令是
blockID = Doc.getElementsByTagName("Block")(0).innerText
它给了我很多html代码仍然附加的值,如
<Block FIPS="120950170151016">
搜索一下,似乎我可能需要使用getAttributes函数(?),但这似乎不是下拉列表中的一个选项,因为我正在使用VBA。这让我想知道我是否没有安装其中一个参考包。
任何见解?
编辑:感谢下面的见解。我尝试过使用Load()而不是LoadXML(),但它似乎仍然没有将任何信息读入对象。错误是“完成此操作所需的数据尚不可用”,并且当代码尝试循环遍历x值时会发生错误。从Locals查看器中清除对象中没有数据。这就是我所拥有的:
Dim oAttribute, item
Dim x As Long
Dim apiURLstub, apiURL As String
apiURLstub = "http://data.fcc.gov/api/block/find?"
'append lat/lon info to URL
Dim lat As Double
Dim lon As Double
lat = Range("A3").Value
lon = Range("B3").Value
apiURL = apiURLstub & "latitude=" & lat & "&longitude=" & lon & "&showall=true"
Dim objXML As Object, node As Object
Set objXML = New MSXML2.DOMDocument
If Not objXML.Load(apiURL) Then 'strXML is the string with XML'
Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
Else
Set node = objXML.getElementsByTagName("intersection")
For x = 0 To node.Length - 1
For Each oAttribute In node(x).Attributes
Debug.Print oAttribute.Value
Next
Next
End If
答案 0 :(得分:0)
在我对VBA XML parsing - looping through child nodes的回答中,我有2个GIF动画,展示如何使用Locals
和Immediate
窗口遍历属性并构建代码。
Sub TestStub()
Dim oAttribute, item
Dim x As Long
Const XMLTEST = "<Response xmlns=""http://data.fcc.gov/api"" status=""OK"" executionTime=""120"">" & _
"<Block FIPS=""120950170151016"">" & _
"<intersection FIPS=""120950170151016""></intersection>" & _
"<intersection FIPS=""120950170151019""></intersection>" & _
"<intersection FIPS=""120950170151015""></intersection>" & _
"</Block>" & _
"<County FIPS=""12095"" name=""Orange""></County>" & _
"<State FIPS=""12"" code=""FL"" name=""Florida""></State>" & _
"<messages>FCC0001: The coordinate lies on the boundary of mulitple blocks, first FIPS is displayed. For a complete list use showall=true to display 'intersection' element in the Block</messages>" & _
"<head></head>" & _
"</Response>"
Dim objXML As Object, node As Object
Set objXML = CreateObject("MSXML2.DOMDocument")
If Not objXML.LoadXML(XMLTEST) Then 'strXML is the string with XML'
Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
Else
Set node = objXML.getElementsByTagName("intersection")
For x = 0 To node.Length - 1
For Each oAttribute In node(x).Attributes
Debug.Print oAttribute.Value
Next
Next
End If
End Sub