Recurse XML file using vbscript

后端 未结 2 1132
借酒劲吻你
借酒劲吻你 2020-12-04 01:13

I am trying to use recursive technique to retrieve xml file. Can somebody help me doing that.

I am trying to read below xml, but not sure the depth of the nested tag

相关标签:
2条回答
  • 2020-12-04 01:26

    You need a recursive Sub to traverse the XML document tree. In principle:

      Dim oFS    : Set oFS  = CreateObject("Scripting.FileSystemObject")
      Dim sFSpec : sFSpec   = oFS.GetAbsolutePathName("..\data\so14975608.xml")
      Dim oXML   : Set oXML = CreateObject("Msxml2.DOMDocument.6.0")
      oXML.load sFSpec
      If 0 = oXML.parseError Then
         recursiveTraversal oXML.documentElement, 0
      Else
         WScript.Echo objMSXML.parseError.reason
      End If
    
    Sub recursiveTraversal(oElm, nIndent)
      WScript.Echo Space(nIndent), oElm.tagName
      If 0 < oElm.childNodes.length Then
         Dim oChild
         For Each oChild In oElm.childNodes
             recursiveTraversal oChild, nIndent + 2
         Next
      Else
         If 0 < oElm.attributes.length Then
            Dim oAttr
            For Each oAttr In oElm.attributes
                WScript.Echo Space(nIndent + 1), oAttr.name, oAttr.value
            Next
         End If
      End If
    End Sub
    

    output for your sample data:

     TestSuites
       TestSuite
         TestCase
           TestStep
            TSName TestStep 1
           TestStep
            TSName TestStep 2
         TestCase
           TestStep
            TSName TestStep 1
           TestStep
            TSName TestStep 2
       TestSuite
        SuiteName Smoke
       TestSuite
        SuiteName Sanity
    

    Based on a more detailed plan - what information do you need to extract/process - you must study some suitable XML documentation (start here) to determine the functions/properties to put in the above skeleton.

    P.S.:

    People who did not buy the above won't profit from this.

    0 讨论(0)
  • 2020-12-04 01:38

    VBScript provides you with tools to parse and process XML structures:

    Set xml = CreateObject("MSXML2.DOMDocument")
    xml.async = False
    xml.load "c:\path\to\foo.xml"
    WScript.Echo xml.xml
    

    You can access elements in the document tree using (among other things) the XPath query language:

    Set nodes = xml.selectnodes("//TestStep[@TSName='TestStep 2']")
    

    The above selects all TestStep nodes anywhere in the tree, which have an attribute TSName with a value TestStep 2.

    Once you have the node(s) you can read or change their attributes:

    WScript.Echo nodes.Length
    WScript.Echo nodes(0).parentNode.nodeName
    WScript.Echo nodes(1).parentNode.nodeName
    
    WScript.Echo nodes(0).text
    nodes(0).text = "foo"
    WScript.Echo nodes(0).text
    WScript.Echo xml.xml
    
    0 讨论(0)
提交回复
热议问题