I've made a small XML pretty printer that works quite well:
Sub PrettyPrint(Parent As IXMLDOMNode, Optional Level As Integer)
Dim Node As IXMLDOMNode
Dim Indent As IXMLDOMText
If Not Parent.ParentNode Is Nothing And Parent.ChildNodes.Length > 0 Then
For Each Node In Parent.ChildNodes
Set Indent = Node.OwnerDocument.createTextNode(vbNewLine & String(Level, vbTab))
If Node.NodeType = NODE_TEXT Then
If Trim(Node.Text) = "" Then
Parent.RemoveChild Node
End If
ElseIf Node.PreviousSibling Is Nothing Then
Parent.InsertBefore Indent, Node
ElseIf Node.PreviousSibling.NodeType <> NODE_TEXT Then
Parent.InsertBefore Indent, Node
End If
Next Node
End If
If Parent.ChildNodes.Length > 0 Then
For Each Node In Parent.ChildNodes
If Node.NodeType <> NODE_TEXT Then PrettyPrint Node, Level + 1
Next Node
End If
End Sub
You call it by passing in the DOMDocument
object and leaving the Level
parameter blank.
- It does an in-place modification of the document.
- You will lose all insignificant whitespace (blanks between XML elements) that might have been there.
- It uses one tab to indent.
- It also indents comments and processing instructions etc.
- it will work with all versions of
DOMDocument
.
Dim XmlDoc as New MSXML2.DOMDocument40
' create/load your xml document
PrettyPrint XmlDoc
MsgBox XmlDoc.xml
There also is an easy way to do it via SAX.