VBScript - Select multiple xml nodes that use a self-closing tag
I know that in vbscript we can use documentElement.SelectNodes() to select multiple xml nodes such as in the following example,
<Vocabulary>
<Word type="noun" level="1">
<English>cat</English>
<Spanish>gato</Spanish>
</Word>
<Word type="verb" level="1">
<English>speak</English>
<Spanish>hablar</Spanish>
</Word>
<Word type="adj" level="1">
<English>big</English>
<Spanish>grande</Spanish>
</Word>
</Vocabulary>
Using:
Set NodeList = objXMLDoc.documentElement.selectNodes("Word/English")
But how can the same be done for nodes without a closing tag that instead use a self-closing bracket:
<Vocabulary>
<Word type="adj" level="1">
<English Text="big" />
<Spanish Text="grande" />
</Word>
</Vocabulary>
Basically I need开发者_C百科 to get an array of nodes like this, and loop through getting the attribute value 'Text', for instance.
If I understand correctly , same thing.
Think of the objXMLDoc.documentElement.selectNodes("Word/English")(index
) such as your array.
An example prints the Text
attributes:
Set NodeList = objXMLDoc.documentElement.selectNodes("Word/English")
For i = 0 To NodeList.length - 1
WScript.Echo NodeList(i).getAttribute("Text")
Next
A few other XPath queries:
<!-- based on this XML -->
<Vocabulary>
<Word type="adj" level="1">
<English Text="big" /><!-- let's change this to "large" -->
<Spanish Text="grande" />
</Word>
</Vocabulary>
1. Select all attributes called Text
Set xmlNodes = xmlDoc.selectNodes("//@Text")
For Each xmlNode in xmlNodes
If xmlNode.Text = "big" Then
xmlNode.Text = "large"
bNodeModified = true
End If
Next
2. Select nodes that contain the attribute Text
Set xmlNodes = xmlDoc.selectNodes("(MySelections/MySelection[@Text])")
For Each xmlNode in xmlNodes
If xmlNode.getAttribute("Text") = "big" Then
xmlNode.setAttribute "Text", "large"
End If
Next
3. Select nodes that contain the attribute Text
AND the value big
Set xmlNodes = xmlDoc.selectNodes("(MySelections/MySelection[@Text='big'])")
For Each xmlNode in xmlNodes
xmlNode.setAttribute "Text", "large"
Next
Whole program:
Dim xmlDoc, xmlNodes, xmlNode, bNodeModified
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = false
xmlDoc.Load "C:\MyFile.xml"
Set xmlNodes = xmlDoc.selectNodes("//@Text")
bNodeModified = false
For Each xmlNode in xmlNodes
If xmlNode.Text = "big" Then
xmlNode.Text = "large"
bNodeModified = true
End If
Next
If bNodeModified Then
xmlDoc.Save strXmlFile
End If
精彩评论