从节点列表中获取第一个节点的属性名称项

下面的代码将打印这个:“GAL”

是否有任何选项打印相同的输出使用“xDoc.SelectNodes”,但没有“列表中的每个节点”? 因为我知道父母将只有一个节点,所以在我看来,我必须使用这个“for”,并且定义新的variables('node')
谢谢你的帮助 !

VBA:

Dim xDoc As DOMDocument Set xDoc = New DOMDocument xDoc.Load ("C:\....\example2.xml") Set list = xDoc.SelectNodes("/animal/cat[(@ID)=""17""]") Dim attr As IXMLDOMAttribute Dim node As IXMLDOMNode Dim childNode As IXMLDOMNode For Each node In list Debug.Print node.Attributes.getNamedItem("Name").Text Next node 

XML:

 <animal> <dog ID="16" Name="Lucy"/> <cat ID="156" Name="Chloe"/> <cat ID="17" Name="GAL"> <child ID="173" Name="Tigger"/> <child ID="1256" Name="Angel"/> <child ID="256" Name="Peanut"/> </cat> <cat ID="18" Name="Charlie"> <child ID="173" Name="Smokey"/> </cat> </animal> 

我不知道你为什么打开一个新的问题,这是重新审视昨天的阅读XML子节点属性与VBA OODOC

无论如何,如果你真的有一个循环运行一个项目的问题(坦率地说,我不知道为什么),那么你可以检查list对象的length

 If list.length=1 Then List.item(0).Attributes.getNamedItem("Name").Text Else 'Do the loop End If 

你不能只是添加一个评论,说你期望for循环运行在一个单一的项目?

重写你的代码

 Sub Tst() Dim xDoc As MSXML2.DOMDocument60 Set xDoc = New MSXML2.DOMDocument60 xDoc.Load ThisWorkbook.Path & "\example2.xml" '<---- my path is different Dim oSingular As MSXML2.IXMLDOMNode Set oSingular = xDoc.SelectSingleNode("/animal/cat[(@ID)=""17""]") Debug.Print oSingular.Attributes.getNamedItem("Name").Text ' Set List = xDoc.SelectNodes("/animal/cat[(@ID)=""17""]") ' Dim attr As IXMLDOMAttribute ' Dim node As IXMLDOMNode ' Dim childNode As IXMLDOMNode ' ' For Each node In List ' Debug.Print node.Attributes.getNamedItem("Name").Text ' Next node End Sub