NRH
NRH

Reputation: 323

VBA DOM Find Specific Nodes With Attributes

I have a large XML file that I'm trying to parse using DOM. What I'm trying to do is only pull information from a node if it's parent contains a specific "id" attribute.

For example, if I only want to pull the TITLE or AUTHOR for books containing "id = Adventure" - how would I do it using 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>

Now using this code:

Sub mySub()

Dim mainWorkBook As Workbook
Dim XCMFILE As Variant
Dim BookType As String
Dim BookTitle As Variant
Dim Title As String
Dim n As IXMLDOMNode
Dim i As Integer

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

XCMFILE.Load (XCMFileName) 'Load XCM File


i = 0

For Each n In XCMFILE.SelectNodes("/catalog/book")
    BookType= n.Attributes.getNamedItem("id").Text 'Search for id attribute within node
    If BookID = "Adventure" Then
        Set BookTitle = = XCMFILE.SelectNodes("/catalog/book/title/text()")
        Title = BookTitle(i).NodeValue
        mainWorkBook.Sheets("Sheet1").Range("B" & i + 3).Value = BookTitle'Prints values into B column
        i = i + 1
    EndIf

Next
End Sub

I don't know how to increment properly to only pull the nodes that fit my specification/category.

Thanks for any tips and pointers - I appreciate it.

Upvotes: 2

Views: 3740

Answers (1)

Mathieu Guindon
Mathieu Guindon

Reputation: 71247

You don't need to increment anything. Just write an XPath query that selects only the nodes you're interested in:

For Each n In XCMFILE.SelectNodes("/catalog/book[@id=""Adventure""]")
    ' n is a book node with the "id" attribute value "Adventure"
Next

Upvotes: 1

Related Questions