VBA访问Web服务和解析结果

时间:2017-03-26 18:10:35

标签: vba soap

我需要解析一个特定的节点(Token),以便我可以在下一个API请求中使用它。我得到了SOAP XML响应(如下所示)。我陷入了这个子例程的最后一行,编译错误:参数不是可选的。一旦我设置了变量LastToken - 我希望在MsgBox中看到它来验证它。似乎找不到合适的语法来解决这个问题。

VBA代码(使用Access 2016)

Sub InvokeAuthenticate()

    'Declare our working variables
    Dim sMsg As String
    Dim sURL As String
    Dim sEnv As String
    Dim LastToken As String
    'Set and Instantiate our working objects
    Set objHTTP = New MSXML2.XMLHTTP
    sURL = "http://netforum.avectra.com/xweb/netforumxmlondemand.asmx"
    'SOAP envelope for submission to the Web Service
    sEnv = "<?xml version=""1.0"" encoding=""utf-8""?>"
    sEnv = sEnv & "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:ns=""http://www.avectra.com/OnDemand/2005/"">"
    sEnv = sEnv & "  <soap:Header/>"
    sEnv = sEnv & "  <soap:Body>"
    sEnv = sEnv & "     <ns:Authenticate>"
    sEnv = sEnv & "          <ns:userName>notdisplayed</ns:userName>"
    sEnv = sEnv & "          <ns:password>notdisplayed</ns:password>"
    sEnv = sEnv & "     </ns:Authenticate>"
    sEnv = sEnv & "  </soap:Body>"
    sEnv = sEnv & "</soap:Envelope>"
    'invoke the web service
    objHTTP.Open "Post", sURL, False
    objHTTP.setRequestHeader "Content-Type", "text/xml"
    objHTTP.send (sEnv)
    MsgBox objHTTP.responseText
    'below is where the trouble starts, I need syntax help

    Dim xmlDoc As New DOMDocument
    xmlDoc.Load (objHTTP.responseText)
    LastToken = xmlDoc.getElementsByTagName(Token)


End Sub

SOAP XML响应成功通过objHTTP.responseText:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Header>
      <AuthorizationToken soap:mustUnderstand="1" xmlns="http://www.avectra.com/OnDemand/2005/">
         <Token>7e6345ef-10c5-4b0b-9731-26db2ebdcd1d</Token>
      </AuthorizationToken>
   </soap:Header>
   <soap:Body>
      <AuthenticateResponse xmlns="http://www.avectra.com/OnDemand/2005/">
         <AuthenticateResult>http://www.avectra.com/OnDemand/2005/</AuthenticateResult>
      </AuthenticateResponse>
   </soap:Body>
</soap:Envelope>

1 个答案:

答案 0 :(得分:0)

这对我有用(从工作表单元加载XML以进行测试):

Dim oDoc As New MSXML2.DOMDocument30
Dim el As Object, txt
Dim XML As String

XML = ActiveSheet.Range("B2").Value

oDoc.validateOnParse = True
oDoc.LoadXML XML

txt = oDoc.getElementsByTagName("Token")(0).Text

Debug.Print txt '>> 7e6345ef-10c5-4b0b-9731-26db2ebdcd1d