我想教自己的VBA和XML的基礎知識來解決我在Excel中工作的特定問題。我正在嘗試使用API來提取經緯度給定的人口普查區塊ID。試圖用VBA來解析html
這裏的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值時發生。從本地瀏覽器清除對象中沒有數據。下面是我得到了什麼:
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
XML!= HTML。改爲使用[Microsoft.XMLDOM](https://msdn.microsoft.com/en-us/library/aa468547.aspx)。 – Comintern
您是否嘗試過使用[Regex](http://stackoverflow.com/a/1732454/1641172)? –
對。 XML。感謝您回答我的愚蠢問題! – jer312