【问题标题】:Looping through XML file elements循环遍历 XML 文件元素
【发布时间】:2018-11-26 01:32:32
【问题描述】:

我在下面有一个 XML 文件。我想遍历这个文件并提取节点节点值,比如对于节点 <com> 获取名称值,然后循环 2 次以获取文件值。我目前可以获取节点 <com> 的值,但不确定如何在内部循环并获取文件节点的值。

<common>
  <com name="Test1.css">
    <file name="Tech.css"/>
    <file name="Comp.css"/> 
  </com>
  <com name="Test2.css">
    <file name="HR.css"/>
    <file name="HR2.css"/> 
  </com> 
</common>
Dim xmlDoc, objNodeList, plot
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("C:\test\combineXML.xml")
WScript.Echo xmlDoc.parseError
Set objNodeList = xmlDoc.getElementsByTagName("com")
If objNodeList.length > 0 then
    For each x in objNodeList
        JobName = x.getattribute("name")
        WScript.Echo JobName
    Next
End If

【问题讨论】:

    标签: xml vbscript


    【解决方案1】:

    你把这弄得太复杂了。只需使用 XPath 表达式从所有 com 节点的子节点中选择 name 属性:

    Set xmlDoc = CreateObject("Msxml2.DOMDocument")
    xmlDoc.async = False
    xmlDoc.load "C:\test\combineXML.xml"
    If xmlDoc.parseError = 0 Then
      For Each x In xmlDoc.selectNodes("//com/*/@name")
        WScript.Echo x.text
      Next
    End If
    

    如果您需要更具体的表达式,请使用//com/file/@name(以防有其他具有name 属性的子节点。

    如果您还需要父节点的属性,则必须像这样修改它:

    Set xmlDoc = CreateObject("Msxml2.DOMDocument")
    xmlDoc.async = False
    xmlDoc.load "C:\test\combineXML.xml"
    If xmlDoc.parseError = 0 Then
      For Each x In xmlDoc.selectNodes("//com/*")
        WScript.Echo x.parentNode.getAttribute("name") & ": " _
          & x.getAttribute("name")
      Next
    End If
    

    【讨论】:

    • 非常好..我怎样才能得到 com 节点的值..就像我想要这样的结果 test1 tech.css comp.css 然后 test2.css HR.css HR2.css
    【解决方案2】:

    您可以使用.ChildNodes 属性

    Dim xmlDoc, objNodeList, plot
    dim fileNodes
    dim comNodeItem
    dim fileNodeItem
    dim fileName, jobName
    
    Set xmlDoc = CreateObject("Msxml2.DOMDocument")
    
    xmlDoc.setProperty "SelectionLanguage", "XPath"
    xmlDoc.load("C:\test\combineXML.xml")
    
    WScript.Echo xmlDoc.parseError
    
    Set objNodeList = xmlDoc.getElementsByTagName("com")
    
    For each comNodeItem in objNodeList
        JobName = comNodeItem.getAttribute("name")
        for each fileNodeItem in comNodeItem.ChildNodes
            fileName = fileNodeItem.getAttribute("name")
            WScript.Echo JobName & ": " & fileName
        next
    Next
    

    如果文件像您的示例一样简单,这将起作用。如果您只想处理file 节点,而忽略其他节点,您也可以再次使用:

        for each fileNodeItem in comNodeItem.getElementsByTagName("file")
    

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 2022-06-11
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多