我知道在vbscript中我们可以使用documentElement.SelectNodes()来选择多个xml节点,如下例所示,
<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>
使用:
Set NodeList = objXMLDoc.documentElement.selectNodes("Word/English")
但是,对于没有结束标记而是使用自闭合括号的节点,如何做同样的事情:
<Vocabulary>
<Word type="adj" level="1">
<English Text="big" />
<Spanish Text="grande" />
</Word>
</Vocabulary>
基本上我需要获得这样的节点数组,并循环获取属性值'Text',例如。
答案 0 :(得分:2)
如果我理解正确,同样的事情。
想想 objXMLDoc.documentElement.selectNodes(“Word / English”)( index
),例如你的数组。
示例打印Text
属性:
Set NodeList = objXMLDoc.documentElement.selectNodes("Word/English")
For i = 0 To NodeList.length - 1
WScript.Echo NodeList(i).getAttribute("Text")
Next
答案 1 :(得分:1)
其他一些XPath查询:
<!-- 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。选择名为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。选择包含属性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。选择包含属性Text
AND 值big
Set xmlNodes = xmlDoc.selectNodes("(MySelections/MySelection[@Text='big'])")
For Each xmlNode in xmlNodes
xmlNode.setAttribute "Text", "large"
Next
整个计划:
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