【问题标题】:Get attributes in xml file using vbscript使用vbscript获取xml文件中的属性
【发布时间】:2013-03-05 08:13:43
【问题描述】:

我正在使用递归方法遍历 xml,并希望确定特定节点是否具有任何属性。这是我尝试过的

第一种方法:使用 foreach 循环获取所有属性的列表,但是这种方法的问题是,如果任何节点没有任何属性,它就会抛出错误

第二种方法:通过作为参数传递的属性名称查找属性并验证它是否返回null,但在这种情况下,我需要将所有属性名称放在手边,这永远不会让我继续使用递归方法。

【问题讨论】:

    标签: xml vbscript


    【解决方案1】:

    看过this的人会买:

    第一种方法是正确的。一个简单的实现:

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

    输出:

     TestSuites
       TestSuite
        SuiteName Regression
        TCName TestCase 1
         TestCase
          TCName TestCase 1
          abc 123
           TestStep
            TSName TestStep 1
           TestStep
            TSName TestStep 2
           NoAttr
             TestSuite
              SuiteName Regression
              TCName TestCase 1
               TestStep
                TSName TestStep 1
         TestCase
          TCName TestCase 2
           TestStep
            TSName TestStep 1
           TestStep
            TSName TestStep 2
       TestSuite
       TestSuite
        SuiteName Sanity
    

    【讨论】:

    • 另外我正在尝试将测试套件、测试用例和测试步骤放入字典对象(嵌套字典)中,但不知道字典的执行情况。如果您对此有所了解。请放点光。
    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多