2017-10-19 61 views
-2

這是我的代碼片段,這部分是讀取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> 
+0

attr爲Dictionary對象,如果屬性值是內部字典,計數器值的一個+ 1。 – Zephyros

+1

如果您沒有看到循環中的任何輸出,則意味着'SelectNodes'不會返回任何節點。這通常發生在XML數據具有名稱空間的情況下。您的實際XML是否包含'xmlns = ...'屬性和/或''節點? –

+0

不,我的XML以 Zephyros

回答

1

試試這段代碼來獲取父節點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屬性: 對我的作品罰款:

enter image description here

+0

BTW您可以在代碼片段前添加'<! - language:lang-vb - >'來修正語法突出顯示。 – Tomalak

+0

@Tomalak感謝您的建議。更新。 – Gurman

+0

需要對象:'objCol.item(...)'錯誤 – Zephyros

0

如果你只想讓所有操作與類型= 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