VBA – 如何检索debug.Print中的键中的XML键

XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <EmpDetails> <Employee> <Name>ABC</Name> <Dept> <Software1> VBA </Software1> <Software2> Windows </Software2> </Dept> <Location>New Delhi</Location> </Employee> <Employee> <Name>XYZ</Name> <Dept> <Software1> VBA </Software1> <Software2> Windows </Software2> </Dept> <Location>Chennai</Location> </Employee> <Employee> <Name>IJK</Name> <Dept> <Software1> VBA </Software1> <Software2> Windows </Software2> </Dept> <Location>Bangalore</Location> </Employee> </EmpDetails> 

VBA

 Sub Test() Dim userBeanList As MSXML2.IXMLDOMNodeList Dim userbean As MSXML2.IXMLDOMNode Dim beanChild As MSXML2.IXMLDOMNode Set xDoc = New MSXML2.DOMDocument xDoc.Load ("C:\data\xml.xml") Set userBeanList = xDoc.SelectNodes("//EmpDetails/Employee") For Each userbean In userBeanList For Each beanChild In userbean.ChildNodes Debug.Print beanChild.nodeName & ":" & beanChild.Text Next beanChild Next userbean End Sub 

我的代码目前从xml打印,如下所示:

 Name:ABC Dept:VBA Windows Location:New Delhi Name:XYZ Dept:VBA Windows Location:Chennai Name:IJK Dept:VBA Windows Location:Bangalore 

我希望它实际上打印

 Name:ABC Dept:VBA Windows Location:New Delhi Name:XYZ Software1:VBA Software2:Windows Location:Chennai Name:IJK Software1: VBA Software2: Windows Location:Bangalore 

在我的第一个例子中,我只是添加了另一个级别(grandChild)到你的循环。

 Sub Example() Dim userBeanList As MSXML2.IXMLDOMNodeList Dim userbean As MSXML2.IXMLDOMNode Dim beanChild As MSXML2.IXMLDOMNode Dim grandChild As MSXML2.IXMLDOMNode Set xDoc = New MSXML2.DOMDocument xDoc.Load ("C:\Users\best buy\Desktop\xml.xml") Set userBeanList = xDoc.SelectNodes("//EmpDetails/Employee") For Each userbean In userBeanList For Each beanChild In userbean.ChildNodes Debug.Print beanChild.nodeName & ":" & beanChild.Text For Each grandChild In beanChild.ChildNodes If Not Left(grandChild.nodeName, 1) = "#" Then Debug.Print grandChild.nodeName & ":" & grandChild.Text Next Next beanChild Next userbean End Sub 

这里是一个使用recursion的例子,它将打印XML的所有分支和叶子,而不需要知道实际的结构。

 Sub RecursiveExample() Dim userBeanList As MSXML2.IXMLDOMNodeList Set xDoc = New MSXML2.DOMDocument xDoc.Load ("C:\Users\best buy\Desktop\xml.xml") Set userBeanList = xDoc.SelectNodes("//EmpDetails/Employee") RecursivePrintNodes userBeanList End Sub Sub RecursivePrintNodes(NodeList As MSXML2.IXMLDOMNodeList) Dim child As MSXML2.IXMLDOMNode For Each child In NodeList If Not Left(child.nodeName, 1) = "#" Then Debug.Print child.nodeName & ":" & child.Text If child.ChildNodes.Length > 0 Then RecursivePrintNodes child.ChildNodes Next End Sub