2015-09-25 64 views
0

我有一個XML文件,它有許多具有相同名稱的節點。我需要到達一個特定的節點,不是按其名稱,也不是按其屬性,而是按的順序出現在XML文件中。例如:如何通過它的編號(順序)到達特定的XML節點?

<category field="X"/> 
<class LN="RF"/> 
<category field="Y"/> 
<p name="state"/> 
<category field="Z"/> 
<category field="A"/> 

所以我需要到達節點<category field="Z"/>例如,不是因爲它的屬性是="Z"但由於其爲了是組category節點在第三。

回答

3

使用節點發生用XPath的[]position()功能:

Public Sub XMLData() 
    Dim XmlFile 
    Dim doc, item 
    Dim fso, stdout 

    Set fso = CreateObject ("Scripting.FileSystemObject") 
    Set stdout = fso.GetStandardStream (1) 

    XmlFile = "C:\Path\To\xmlfile.xml" 
    doc.Load XmlFile 

    For Each item In doc.SelectNodes("//category[3]") 'OR //category[position()=3]' 
    stdout.WriteLine item.Attributes.ItemOf("field").InnerText 
    Next 

    Set fso = Nothing 
End Sub 
0

XPath expression選擇<category>節點,然後使用item方法從結果集合選擇的第n個元素:

xmldata = "<root>" & _ 
    "<category field=""X""/>" & _ 
    "<class LN=""RF""/>" & _ 
    "<category field=""Y""/>" & _ 
    "<p name=""state""/>" & _ 
    "<category field=""Z""/>" & _ 
    "<category field=""A""/>" & _ 
    "</root>" 

Set xml = CreateObject("Msxml2.DOMDocument") 
xml.async = False 
xml.loadXml xmldata 

If xml.parseError <> 0 Then 
    WScript.Echo xml.parseError.Reason 
    WScript.Quit xml.parseError 
End If 

Set categories = xml.selectNodes("//category") 
Set thirdCategory = nodes.item(2) 

WScript.Echo node.getAttribute("field") 

注意索引是從零開始的,所以你需要使用第三個元素的索引2。