根据VBScript中的另一个属性获取XML属性

时间:2017-04-17 20:32:56

标签: xml xpath vbscript

我有以下从SOAP API返回的XML:

<?xml version="1.0" encoding="UTF-8"?>
<results>
<result>
<field name="accountnumber" value="100035" />
<field name="occupantcode" value="11" />
<field name="otherfield" value"do not care about this one" />
</result>
</results>

我正在尝试使用VBScript将帐号加载到名为AcctNum的变量中,将另一个加载到OccCode中。我是XPath查询的新手。我正在尝试这样的事情:

Set ANumNode = xmlResponse.SelectNodes("//results/result/field[@accountnumber]")
For Each objSite In ANumNode
  AcctNum = objSite.SelectSingleNode("accountnumber").Text
Next

但当然这种情况非常激烈。响应中实际上有大约20个字段节点,其中我只关注其中的4个。我无法更改输出XML的格式。

2 个答案:

答案 0 :(得分:1)

  1. 您的XML格式不正确。
  2. 您需要了解节点和属性之间的差异
  3. 使用文档(start here)通过此示例代码工作:

    Option Explicit
    
    Dim oFS    : Set oFS  = CreateObject( "Scripting.FileSystemObject" )
    Dim sFSpec : sFSpec   = oFS.GetAbsolutePathName(".\43459134.xml")
    Dim oXml   : Set oXml = CreateObject("Msxml2.DOMDocument")
    
    oXml.setProperty "SelectionLanguage", "XPath"
    oXml.async = False
    oXml.load sFSpec
    
    If 0 = oXml.parseError.errorCode Then
       WScript.Echo "loaded:", sFSpec
       WScript.Echo "root:", oXml.documentElement.tagName
    
       Dim sXPath, ndlResults, ndResult
    
       sXPath = "/results/result"
       Set ndlResults = oXml.selectNodes(sXPath)
       If 0 = ndlResults.length Then
          WScript.Echo "no '" & sXPath & "' found"
       Else
          WScript.Echo "found", ndlResults.length, "node(s) for '" & sXPath & "'"
          For Each ndResult In ndlResults
             WScript.Echo "ndResult.tagName:", ndResult.tagName
             Dim AcctNum : AcctNum = ndResult.selectSingleNode("field[@name=""accountnumber""]").getAttribute("value")
             Dim OccCod  : OccCod  = ndResult.selectSingleNode("field[@name=""occupantcode""]").getAttribute("value")
             WScript.Echo AcctNum, OccCod
          Next
       End If
    Else
       WScript.Echo "errorCode:", oXml.parseError.errorCode
       WScript.Echo oXml.parseError.reason
    End If
    

    输出:

    cscript 43459134.vbs
    loaded: E:\work\proj\soa\tmp\43459134.xml
    root: results
    found 1 node(s) for '/results/result'
    ndResult.tagName: result
    100035 11
    

    更新wrt评论:

    脚本&#39;工作&#39;对于你发布的(更正的).xml;如果/results/result位于树的下方,请尝试/REALDOCROOT/pi/pa/pi/results/result或不太具体的//results/result。或者:发布实际输入。

答案 1 :(得分:0)

我最终放弃了XPath查询,而是构建了自己的解析器,因为结构将是静态的:

Function retrieveValue(XMLblock, fieldname)
  start = 1
  '***Find field
  start = InStr(start, XMLBlock, "" & fieldname & "")
  '***Find value tag
  start = InStr(start, XMLBlock, "value")
  '***Find end quote for value
  endquote = InStr(start+7, XMLBlock, """")
  retrieveValue = Mid(XMLBlock, start+7, endquote-start-7)
End Function

不是最优雅的代码,但它可以工作,以便我可以继续我的项目。谢谢大家的帮助。