Recursively walking the DOM of an XMLNode or XMLDocument
By Ken Fitzpatrick
The following two overloaded shared functions (static methods) can be used to either return a list of all nodes in an XMLDocument or walk the DOM of an XMLNode and return a string representation of it. The first function "DisplayXMLNodes(ByVal xmlStr As String) As String" makes use of the second function "DisplayXMLNodes(ByVal xmlNode As XmlNode, ByVal indent As Integer) As String" which calls itself recursively.
' This function will return a list of all the nodes and values in an XML Document.
Public Shared Function DisplayXMLNodes(ByVal xmlStr As String) As String
Dim xmlDoc As New XmlDocument
If xmlStr.Trim <> "" Then
xmlDoc.LoadXml(xmlStr)
'We don't care about the whitespace elements being displayed
xmlDoc.PreserveWhitespace = False
'Call DisplayNodeInformation
Return DisplayXMLNodes(xmlDoc, 0) & vbCrLf
Else
Return ""
End If
End Function
'This recursive function will walk the DOM of an XMLNode and return a string
representation of it.
Public Shared Function DisplayXMLNodes(ByVal xmlNode As XmlNode, ByVal indent
As Integer) As String
Dim results As String = ""
Dim childNode As XmlNode
If xmlNode.Name.StartsWith("#") Then
results &= xmlNode.Value
Else
results = results & vbCrLf & Space(indent) & xmlNode.Name
& ": "
End If
For Each childNode In xmlNode.ChildNodes
results = results & DisplayXMLNodes(childNode, indent + 3)
Next
Return results
End Function
Related FAQs
The following code snippet is a shared function (or static method) that takes an XML String (string type) and a pathname for an XSLT file and returns a string of XML that has been transformed based on the rules in the XSLT file.
Recursively walking the DOM of an XMLNode or XMLDocument (507 Views)