VBA以XML格式读取ChildNode的ChildNode的ChildNode

时间:2014-08-28 08:23:07

标签: xml excel vba excel-vba

首先"谢谢"你有时间调查这个。

如果有人能给我一个解决问题的示例代码/代码段,我真的很感激。 我很难通过VBA在XML中读取ChildNode的ChildNode的ChildNode。

示例XML:sample XML file

我当前的代码给出错误:RUN TIME ERROR 6 OVERFLOW。

我希望输出像这样

ID       VIEW DESCRIPTION   COLUMNNAME
55494   Asset Management        Actual Price.Value
55464   Change Management      CAB Manager ( Change Co-ord )
55464   Change Management       Manufacturer (2)
55464   Change Management       Change Timing
55308   Incident Management     Submitter
55308   Incident Management     Submit Date
55308   Incident Management     Secure Work Log
55308   Incident Management     Number of Attachments
73189   Knowledge Management    
73189   Knowledge Management    ArticleCompany
73189   Knowledge Management    ArticleDocID

当前代码

Sub test()
Dim Init As Integer
Dim xmlDoc As New DOMDocument
Dim DomNode1  As IXMLDOMElement
Dim DomNode2  As IXMLDOMElement
Dim node As IXMLDOMNode
Dim childNode1 As IXMLDOMNode
Dim childNode2 As IXMLDOMNode
Dim childNode6 As IXMLDOMNode
Dim elements As Object
Dim el As Variant

Init = 7

'Worksheets("Report_Details").Select
xmlDoc.Load ("C:\DRIVE\BMC\DSS\01_DSS_NExT\SP_1\IN APP\Automation_YF\Tools\TEST_xml.xml")
child_count = 0
For Each DomNode1 In xmlDoc.getElementsByTagName("view")
For Each childNode1 In DomNode1.getElementsByTagName("id")
For Each childNode2 In DomNode1.getElementsByTagName("viewDescription")
For Each childNode6 In DomNode1.getElementsByTagName("columnName")

                    ActiveSheet.Cells(Init, 6).Value2 = childNode6.Text
    ActiveSheet.Cells(Init, 2).Value2 = childNode2.Text
ActiveSheet.Cells(Init, 1).Value2 = childNode1.Text

child_count = child_count + 1
Init = Init + 1
                   Next childNode6
              Next childNode2
Next childNode1
Next DomNode1
End Sub

1 个答案:

答案 0 :(得分:1)

尝试使用SelectNodes()SelectSingleNode()传递合适的XPath表达式作为参数,例如:

Init = 7
xmlDoc.Load ("C:\DRIVE\BMC\DSS\01_DSS_NExT\SP_1\IN APP\Automation_YF\Tools\vw_pun_atm_dv04.xml")
For Each DomNode1 In xmlDoc.SelectNodes("//view[id and viewDescription and columnName]")
    ActiveSheet.Cells(Init, 6).Value2 = DomNode1.SelectSingleNode("./id").Text
    ActiveSheet.Cells(Init, 2).Value2 = DomNode1.SelectSingleNode("./viewDescription").Text
    ActiveSheet.Cells(Init, 1).Value2 = DomNode1.SelectSingleNode("./columnName").Text
    Init = Init + 1
Next DomNode1