在VBA Excel中解析XML DOM - 父母和子女

时间:2016-11-08 00:30:00

标签: xml excel vba excel-vba dom

我想从这个xml文件中提取一个" serialnum"的列表。对于所有曲目,以及"类别"每个serialnum的父级compactdisc。即。

00001   Type A
00002   Type A
...
00007   Type B
00008   Type B

我想出了如何提取序列号列表,但是如何从几个级别提取相关类别" up" XML链?我很乐意重新调整阵列的大小,但为了简单起见,我将其保留为100。我也对多维数组感到满意,所以也许我可以写一个包含" Serialnum"的二维数组。在第一列和"类别"在第二栏?我很乐意编写一个循环(或循环循环)来迭代这个场景,但我如何调用来获得"类别"每个Serialnum的价值?谢谢。

XML:

<?xml version="1.0"?>
<compactdiscs>
  <compactdisc category="Type A">
    <artist type="individual">Frank Sinatra</artist>
    <title numberoftracks="4">In The Wee Small Hours</title>
   <tracks>
      <track serialnum="00001">In The Wee Small Hours</track>
      <track serialnum="00002">Mood Indigo</track>
      <track serialnum="00003">Glad To Be Unhappy</track>
      <track serialnum="00004">I Get Along Without You Very Well</track>
   </tracks>
    <price>$12.99</price>
  </compactdisc>
  <compactdisc category="Type B">
    <artist type="band">The Offspring</artist>
    <title numberoftracks="5">Americana</title>
   <tracks>
      <track serialnum="00005">Welcome</track>
      <track serialnum="00006">Have You Ever</track>
      <track serialnum="00007">Staring At The Sun</track>
      <track serialnum="00008">Pretty Fly (For A White Guy)</track>
   </tracks>
    <price>$12.99</price>
  </compactdisc>
</compactdiscs>

VBA(Excel)。这段代码只提取了一系列的Serialnum,没有&#34;类别&#34;数据,但我想添加&#34;类别&#34;数据

Sub CDload()
'Create new sheet for ouput
'Set x = ThisWorkbook.Worksheets.Add

'define the object and load the first XML sheet
Set Target_XML_File = CreateObject("Microsoft.XMLDOM")
Target_XML_File.Load (ActiveWorkbook.Path & "\CDs.xml")
Set CurrentNode = Target_XML_File.SelectNodes("/compactdiscs/compactdisc/tracks/track/@serialnum")

Dim arrayx() As String
ReDim arrayx(100, 0)

For i = 0 To (CurrentNode.Length - 1)
    arrayx(i, 0) = CurrentNode(i).NodeValue
Next i

'write array to worksheet, starting on row 2
ActiveSheet.Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(101, 1)) = arrayx

End Sub

1 个答案:

答案 0 :(得分:0)

我回答了自己的问题。解决方案是使用.ParentNode语法结合.getAttribute(“XXXXXX”)语法。请注意,我还更改了“选择节点”语法,以便不是最初选择属性,而是选择元素,然后使用“getattribute(”XXXXXX“)语法。请参阅下面的工作代码。

Sub CDload()

'define the object and load the first XML sheet
Set Target_XML_File = CreateObject("Microsoft.XMLDOM")
Target_XML_File.async = False
Target_XML_File.Load (ActiveWorkbook.Path & "\CDs.xml")
Set CurrentNode = Target_XML_File.SelectNodes("/compactdiscs/compactdisc/tracks/track")

Dim arrayx() As String
ReDim arrayx(100, 0)
Dim arrayx2() As String
ReDim arrayx2(100, 0)

For i = 0 To (CurrentNode.Length - 1)
    arrayx(i, 0) = CurrentNode(i).getAttribute("serialnum")
    arrayx2(i, 0) = CurrentNode(i).ParentNode.ParentNode.getAttribute("category")
Next i


'write array to worksheet, starting on row 2
ActiveSheet.Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(101, 1)) = arrayx
ActiveSheet.Range(ActiveSheet.Cells(1, 2), ActiveSheet.Cells(101, 2)) = arrayx2

End Sub