2015-09-25 63 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。