VBA DOM 特定节点和属性 ID

VBA DOM Specific Node and Attribute ID

我有一个很大的 XML 文件,我正在尝试使用 DOM 进行解析。我想做的是从属性节点中提取信息,如果它的子节点包含特定值。

例如,

<?xml version="1.0"?>
<catalog>
<book id="Adventure">
   <author>Gambardella, Matthew</author>
   <title>XML Developer's Guide</title>
   <price>44.95</price>
</book>
<book id="Adventure">
   <author>Ralls, Kim</author>
   <title>Midnight Rain</title>
   <price>5.95</price>
</book>
<book id="Adventure">
   <author>Boal, John</author>
   <title>Mist</title>
   <price>15.95</price>
</book>
<book id="Mystery">
   <author>Ralls, Kim</author>
   <title>Some Mystery Book</title>
   <price>9.95</price>
</book>
</catalog>

所以从这里,假设我想找到作者写的书 "Ralls, Kim":

Sub mySub()

Dim mainWorkBook As Workbook
Dim XMLFile As Variant
Dim BookType As String
Dim Author As Variant
Dim athr As String
Dim n As IXMLDOMNode
Dim i As Integer

Set mainWorkBook = ActiveWorkbook
Set XMLFILE = CreateObject("Microsoft.XMLDOM")

XMLFILE.Load (XCMFileName) 'Load XCM File

Set Author = XMLFILE.SelectNodes("/catalog/book/author/text()")
For i = 0 To (Author.Length - 1)
    athr= Author(i).NodeValue 
    If athr = "Ralls, Kim" Then
        mainWorkBook.Sheets("Sheet1").Range("C" & i + 3).Value = athr
    End If
Next
End Sub

现在,如果我想在下一列中显示图书类型(即 "Adventure/Mystery"),我该怎么做呢?我正在尝试向后思考,但我什至不知道如何开始。

我知道我可以使用 XPath 和 IXMLDOMNode 来获取属性 id,但我只是不知道如何真正去做这件事,因为它似乎是倒退的。

感谢您的任何提示和指点 - 我很感激。

您可以 "up" 几个步骤到达父 "book" 元素并从那里读取 id 属性:

Sub mySub()

Dim mainWorkBook As Workbook
Dim XMLFile As Variant
Dim BookType As String
Dim Author As Variant
Dim athr As String
Dim n As IXMLDOMNode
Dim i As Long, x As Long

    Set mainWorkBook = ActiveWorkbook
    Set XMLFile = CreateObject("Microsoft.XMLDOM")

    XMLFILE.Load (XCMFileName) 'Load XCM File

    x = 3

    Set Author = XMLFile.SelectNodes("/catalog/book/author/text()")
    For i = 0 To (Author.Length - 1)
        athr = Author(i).NodeValue
        If athr = "Ralls, Kim" Then
            With mainWorkBook.Sheets("Sheet1")
            .Range("C" & x).Value = athr
            .Range("D" & x).Value = _
                Author(i).ParentNode.ParentNode.getAttribute("id")
            End With
            x = x + 1
        End If
    Next
End Sub