VBScript无法迭代XML节点
问题描述:
这是我的代码片段,这部分是读取XML文件并获取操作的最后一个子属性。在这种情况下,我想获得类型C.事实是,脚本跳过了整个For
循环,正如我所说的回声所证明的那样。我做了一些搜索,但仍然无法找到我的代码出了什么问题。VBScript无法迭代XML节点
Set FSO = CreateObject("Scripting.FileSystemObject")
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
counter = 0
xmlDoc.Load(mostrecent(i).Name)
Set colNodes = xmlDoc.SelectNodes("/Runs/Run/Operations")
WScript.Echo counter '<--appears
For Each objNode In colNodes
WScript.Echo counter '<--didn't appear
If Attr.Exists(objNode.LastChild.GetAttribute("type")) Then
counter = counter + 1
WScript.Echo counter
End If
Next
XML:
<Runs>
<Run>
<Operations>
<Operation type="A"></Operation>
<Operation type="B"></Operation>
<Operation type="C"></Operation>
</Operations>
</Run>
</Runs>
答
试试这段代码来获取父节点Operations
Dim objXML, strPath, objCol
strPath = mostrecent(i).Name
Set objXML = CreateObject("Microsoft.XMLDOM")
objXML.async=False
objXML.load strPath
strQuery = "/Runs/Run/Operations/Operation"
Set objCol = objXML.selectNodes(strQuery) 'collection of all the <Operation> nodes
MsgBox objCol.item(objCol.length-1).attributes.getnameditem("type").text
更新的最后一个孩子的type
属性: 对我的作品罚款:
答
如果你只想让所有操作与类型= C,你可以使用下面的代码
Set objXML = CreateObject("MSXML2.DOMDocument.6.0")
With objXML
.SetProperty "SelectionLanguage", "XPath"
.ValidateOnParse = True
.Async = False
.Load "C:\Users\Pankrit\Desktop\test.xml"
End With
Set nodesC = objXML.DocumentElement.SelectNodes("/Runs/Run/Operations/Operation[@type='C']")
If nodesC.Length >= 1 Then
For Each nodeC In nodesC
MsgBox nodeC.NodeName
Next
End If
attr为Dictionary对象,如果属性值是内部字典,计数器值的一个+ 1。 – Zephyros
如果您没有看到循环中的任何输出,则意味着'SelectNodes'不会返回任何节点。这通常发生在XML数据具有名称空间的情况下。您的实际XML是否包含'xmlns = ...'属性和/或''节点? –
不,我的XML以 –
Zephyros