【发布时间】:2016-03-30 19:16:04
【问题描述】:
我有一些代码在解析之前发出 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 .
我尝试创建函数,但不确定将其定义为什么类型,所以我选择了对象:
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
但不幸的是它没有工作,我调用的函数是错误的吗?是不是类型不对?我什至可以这样做吗?哈哈
干杯
【问题讨论】: