r/visualbasic • u/8_bit_armada_II • 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.
2
u/JasonHenley Oct 04 '19
Personally I like using XElement instead.
Check your syntax on secondNode, though. I'm guessing it should be <secondNode desc="data stuff"> and not be a self closing tag, as I'm assuming element, random, and balloon are supposed to be enclosed within secondNode, correct?
Since you want to return only the third level nodes, you can have a nested for loop grab it for you:
Dim flatXML As String = "<firstNode><secondNode desc=""data stuff""><element desc=""Something""/><random desc=""toast""/><balloon desc=""float""/></secondNode></firstNode>"
Dim xmlDocument As XElement = XElement.Parse(flatXML)
Dim thirdLevelElementNames As New List(Of String)
For Each secondLevelElement As XElement In xmlDocument.Elements
For Each thirdLevelElement As XElement In secondLevelElement.Elements
thirdLevelElementNames.Add(thirdLevelElement.Name.LocalName)
Next
Next
MsgBox(String.Join(vbCrLf, thirdLevelElementNames))
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.