Looping through XML file elements

2020-07-22 18:05发布

问题:

I have a XML file below. I want to loop through this file and extract the node node value, like for node <com> get the name value and then loop 2 times to get the file values. I can currently get the value for the node <com> but am unsure how to loop inside and get the values for file node.

<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

回答1:

You can use the .ChildNodes Property

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

This will work if the file is as simple as your example. If you want only file nodes to be processed, and others ignored, you can also just use again:

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


回答2:

You're making this too complicated. Just select the name attribute from the child nodes of all com nodes with an XPath expression:

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

Use //com/file/@name if you need the expression to be more specific (in case there are other child nodes with a name attribute.

If you also want attributes from a parent node, you'll have to modify it like this:

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


标签: xml vbscript