我有一些代码可以发出HTTP请求,并在解析之前从API中提取XML。
我的代码的HTTP请求部分始终相同,唯一更改的参数是我发送请求的URL。我想知道我是否可以将请求转换为函数?
Set xmldoc = CreateObject("Msxml.DOMDocument")
Set httpReq = CreateObject("WinHttp.WinHttprequest.5.1")
xmldoc.async = False
httpReq.Open "GET", myUrl, False
httpReq.setRequestHeader "Content-Type", "text/xml"
If Sheet2.proxyStatus = "ON" Then
httpReq.setProxy 2, Sheet2.proxyServer, ""
ElseIf Sheet2.proxyStatus = "OFF" Then
httpReq.setProxy 0, "", ""
End If
httpReq.setTimeouts -1, -1, -1, -1
httpReq.send request
xmldoc.LoadXML httpReq.responseText
Set xmlElement = xmldoc.DocumentElement
在发出请求后,我使用这样的代码来解析XML中的数据:
TotalSessions = xmlElement.SelectSingleNode("//Row[@rowKey='Sessions']/Value[@columnId='SESSIONS']").Text
解析信息的代码不能包含在函数中,因为它正在寻找的节点和它所分配的变量是唯一的,而且需要很多,但它需要能够读取函数下载的XML
我尝试过创建函数,但我不确定将它定义为什么类型,所以我选择了Object:
Function fetchXML(url As String) As Object
Set xmldoc = CreateObject("Msxml.DOMDocument")
Set httpReq = CreateObject("WinHttp.WinHttprequest.5.1")
xmldoc.async = False
httpReq.Open "GET", url, False
httpReq.setRequestHeader "Content-Type", "text/xml"
If Sheet2.proxyStatus = "ON" Then
httpReq.setProxy 2, Sheet2.proxyServer, ""
ElseIf Sheet2.proxyStatus = "OFF" Then
httpReq.setProxy 0, "", ""
End If
httpReq.setTimeouts -1, -1, -1, -1
httpReq.send request
xmldoc.LoadXML httpReq.responseText
Set xmlElement = xmldoc.DocumentElement
End Function
然后我尝试调用函数并解析一些信息:
fetchXML (coukChannels30DayUrl)
coukPPCSessionsSS = xmlElement.SelectSingleNode("//Row[@rowKey='1#11588418521354:1158842490346']/Value[@columnId='SESSIONS']").Text
但遗憾的是它无法正常工作,我是否将该功能称为错误?这是错误的类型吗?我甚至可以这样做吗?洛尔
干杯
答案 0 :(得分:1)
好的,我让它工作,我只需要在函数中更改这一行:
Set xmlElement = xmldoc.DocumentElement
对此:
Set fetchXML = xmldoc.DocumentElement
然后在sub:
中更改此行fetchXML (coukChannels30DayUrl)
对此:
Set xmlElement = fetchXML(coukChannels30DayUrl)
它的工作非常好,适合功能。