我無法弄清楚,爲什麼我的代碼是不承認的變量名「HourlySchedule」 XML響應文本。當它到達:For Each HourlySchedule In Resp.getElementsByTagName("HourlySchedule")
,它會跳到結束,而不是循環直通每個標籤。我試過幾個不同的標籤名稱,但它似乎不起作用。有什麼建議麼?getElementsByTagName來不工作
我的VBA代碼:
Sub Button1_Click()
Dim URL As String: URL = "webaddress here"
Dim mfile As String
mfile = "<?xml version=" & """" & "1.0" & """" & "?><Envelope xmlns=" & """" & "http://schemas.xmlsoap.org/soap/envelope/" & """" & "><Header/><Body><QueryRequest xmlns=" & """" & "http://markets.midwestiso.org/dar/xml" & """" & "><QueryMarketResults day=" & """" & "2017-03-05" & """" & "><LocationName>Rug</LocationName></QueryMarketResults></QueryRequest></Body></Envelope>"
Set Req = New WinHttp.WinHttpRequest
With Req
.Open "POST", URL, False
.SetClientCertificate "CURRENT_USER\MY\name"
.SetRequestHeader "content-type", "text/xml"
.Send (mfile)
.WaitForResponse
End With
Dim Resp As New MSXML2.DOMDocument60
Resp.LoadXML Req.ResponseText
if Resp.loadxml (Req.ResponseText) then
MsgBox "ok" else
MsgBox "err"
end if
Dim HourlySchedule As IXMLDOMNode
For Each HourlySchedule In Resp.getElementsByTagName("HourlySchedule") ''this is where my problem is
Debug.Print "test"
Next HourlySchedule
End Sub
這裏是我試圖解析XML:
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<QueryResponse xmlns="http://markets.midwestiso.org/dart/xml">
<MarketResults day="2017-03-05">
<Location name="OTP.RUGBY1_IBR">
<HourlySchedule hour="1">
<ClearedEnergy MW="-6" virtualMW="0" price="7" capped="false"/>
<ClearedReg MW="0" price="10.18" capped="false"/>
<ClearedSpin MW="0" price="1" capped="false"/>
<ClearedSupp MW="0" price="0.5" capped="false"/>
<ClearedRampCapabilityUp MW="0" price="0"/>
<ClearedRampCapabilityDown MW="0" price="0"/>
</HourlySchedule>
<HourlySchedule hour="2">
<ClearedEnergy MW="-2" virtualMW="0" price="5.3" capped="false"/>
<ClearedReg MW="0" price="8.06" capped="false"/>
<ClearedSpin MW="0" price="1" capped="false"/>
<ClearedSupp MW="0" price="0.5" capped="false"/>
<ClearedRampCapabilityUp MW="0" price="0"/>
<ClearedRampCapabilityDown MW="0" price="0"/>
</HourlySchedule>
</Location>
</MarketResults>
</QueryResponse>
</Body>
</Envelope>
'myfile'是任何東西,但不是XML。請製作一個語法上有效的VB字符串或者包含語法上有效的XML - 或者將XML文件放入單獨的代碼塊中以供參考。 – Tomalak
最可能的解釋是,有分析錯誤,並沒有真正加載的響應文件。檢查['parseError'屬性](https://msdn.microsoft.com/en-us/library/ms756041(v = vs.85).aspx)(實際上你總是會在加載後檢查解析錯誤一個XML文檔)。在更普遍的情況下,而不是'WinHttp.WinHttpRequest',我建議使用'MSXML2.XMLHTTP60'請求對象,因爲這會透明地做XML解析你(只是訪問其['responseXml'財產(https://開頭msdn.microsoft.com/en-us/library/ms757066(v=vs.85).aspx))。 – Tomalak
感謝您的反饋,我對解析XML有點新。你能舉一個例子,說明如何讓myfile語法上有效的VB字符串?謝謝。 – guice99