如何使用 Excel VBA 导入 XML 数据?

How do I import XML data using Excel VBA?

我正在尝试从 XML 文件中导入数据,如下所示:

<library>
<book>
<title>aaa</title>
<author>aaa-author</author>
</book>
<book>
<title>bbb</title>
<author>bbb-author</author>
</book>
<book>
<title>ccc</title>
</book>
</library>

(注意第三本书对作者没有价值)

我想获得一个 Excel table,其中每本书的数据都显示在一行中。问题是我不明白我必须如何在书本节点上循环以获得它们的子值。

我正在编写这样的代码:

Set mainWorkBook = ActiveWorkbook
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
XMLFileName = "C:\example.xml"
oXMLFile.Load (XMLFileName)
Set Books = oXMLFile.SelectNodes("/book")
For i = 0 To (Books.Length - 1)
   ' I cannot understand this part
Next

添加对 Microsoft XML 6.0 的引用(工具 -> 引用 ...)。这将允许您输入变量 (Dim book As IXMLDOMNode),这将为您提供 Intellisense。

然后可以使用下面的代码,遍历所有的book元素,将titleauthor保存到一个二维数组中(如果有的话) ,然后将该数组粘贴到 Excel 工作表中:

Dim oXMLFile As New DOMDocument60
Dim books As IXMLDOMNodeList
Dim results() As String
Dim i As Integer, booksUBound As Integer
Dim book As IXMLDOMNode, title As IXMLDOMNode, author As IXMLDOMNode

'Load XML from the file
oXMLFile.Load "C:\example.xml"

'Get a list of book elements
Set books = oXMLFile.SelectNodes("/library/book")
booksUBound = books.Length - 1

'Create a two-dimensional array to hold the results
ReDim results(booksUBound, 1)

'Iterate through all the book elements, putting the title and author into the array, when available
For i = 0 To booksUBound
    Set book = books(i) 'A For Each loop would do this automatically, but we need the
                        'index to put the values in the right place in the array
    Set title = book.SelectSingleNode("title")
    If Not title Is Nothing Then results(i, 0) = title.Text
    Set author = book.SelectSingleNode("author")
    If Not author Is Nothing Then results(i, 1) = author.Text
Next

'Paste the results into the worksheet
Dim wks As Worksheet
Set wks = ActiveSheet
wks.Range(wks.Cells(1, 1), wks.Cells(books.Length, 2)) = results

链接:

参考文献: