r/visualbasic • • Oct 04 '19

XML Node Names

<firstNode>
   <secondNode="data stuff"/>
        <element desc="Something"/>
        <random desc="toast"/>
        <balloon desc="float"/>
        [...] 

Given an XML such as the above, with hundreds of nodes, I want to return an array:

  • arr(0) = "element"

  • arr(1) = "random"

  • arr(2) = "balloon"

And on and on for however long my array needs to be to capture those node names. The node names can change, but will always be at the same level. I basically have the following:

strQuery = "/firstNode/secondNode"
Set genNode = doc.documentElement
Set targNode = genNode.SelectNodes(strQuery)

For Each x In targNode
	Set objNode = x.firstChild
    strResult = objNode.nodeName & ","
Next

arrRes = Split(strResult, ",")

It's returning "element" and nothing else. I can't figure out how to get all the nodenames under secondNode.

5 Upvotes

4 comments sorted by

View all comments

2

u/sgc2000 Oct 04 '19

That for loop looks a little wrong, you aren't appending onto strResult you are just replacing. Debug and check targNode contains all of the elements first and then go from there.

1

u/JasonHenley Oct 04 '19

Yep, just change it to strResult &= objNode.nodeName & ","

However, instead of appending a long string only to split it later, why not use List(Of String) to begin with?

Dim arrRes as New List(Of String)

...

For Each x In targNode
    Set objNode = x.firstChild
    arrRes.Add(objNode.nodeName)
Next

1

u/8_bit_armada_II Oct 04 '19

Sorry, that's what I am using. I mistyped.

The issue is that first child always returns the first child, and next sibling won't work.