NRH
NRH

Reputation: 323

VBA Start at first node if it exists - using If Is Nothing

How can I increment through each parent node starting from the first to the last and apply:

For Each n In XMLFile.SelectNodes("/catalog/book")
    If XMLFile.SelectSingleNode("/catalog/book/banana") Is Nothing Then
        MsgBox ("banana not here")
    Else
        MsgBox ("banana found")
    End If
Next

banana does not exist in the first book:

?xml version="1.0"?>
<catalog>
<book id="Adventure">
   <author>Ralls, Kim</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>
   <banana>ring</banana>
</book>
<book id="Adventure">
   <author>Ralls, Kim</author>
   <title>Mist</title>
   <price>15.95</price>
   <banana>ring</banana>
</book>
<book id="Mystery">
   <author>Ralls, Kim</author>
   <title>Some Mystery Book</title>
   <price>9.95</price>
   <banana>ring</banana>
</book>
</catalog>

Current Output: "banana found" "banana found" "banana found" "banana found"

Upvotes: 1

Views: 179

Answers (1)

Comintern
Comintern

Reputation: 22195

You're just repeating the search again from the top level node here...

If XMLFile.SelectSingleNode("/catalog/book/banana") Is Nothing Then

...so you always get the first banana node back. You need to be operating on 'n', not 'XMLFile':

If n.SelectSingleNode("banana") Is Nothing Then

Remember, you're traversing a hierarchy.

Upvotes: 2

Related Questions