For some reason I can't find a simple answer to this question anywhere.
Given any domdocument e.g.
<root><div id="value" name="arga"><b>bold</b></div></root>
I want to simply loop through each node and print the node name, and list any attribute names and their values, if any. e.g. the above snippet would output:
root div id = value name = arga b
Pseudo-coded, it might look like this:
Function traverse(n)
load the root node n, and print its name
does the root node n have attributes? if yes, print them and their values
if the root node n have child node(s) Then
for each childnode in child nodes
traverse(childnode),
loop
Else 'no child nodes
If sibling node(s) exist Then
for each sibling node in sibling nodes
traverse(sibling node)
Next
End If
End If
traverse = results
End Function
Every example I can find involve selecting specific nodes, and specific named attributes.
Here is what I have so far, but it fails when used recursively.
Dim oDoc : Set oDoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
If oDoc.LoadXML("<root d=""sdfgf""><div id=""asdfadfA"">slkdfhga</div><div id=""asdfadfA"">slkdfhga<b>this</b></div></root>") Then
echo traverse(oDoc.documentElement)
End If
Function traverse(n)
Dim s
s = s & typename(n) & "<br />"
s = s & n.nodename & "<br />"
s = s & n.nodetype & "<br />"
'any attributes?
Set oAttributes = n.attributes
If isObject(oAttributes) Then
If oAttributes.length > 0 Then
'print attribs
s = s & "---> has attributes <br />"
For each oAttribute in oAttributes
s = s & "--->" & oAttribute.Name & " = " & oAttribute.Value
Next
End If
End If
'any children?
For Each oChildNode in n.childNodes
'print child
s = s & typename(oChildNode) & "<br />"
s = s & oChildNode.nodename & "<br />"
'recursive
s = s & traverse(oChildNode)
Next
traverse = s.Value
End Function