Friday, 20 October 2017

VBA - Ease Xml debugging wth Xml document pretty print

I like Xml and will frequently choose to work with an Xml document carrying data rather than define a ton of type definitions in VBA but this means the Locals and the Watches window show a big blob of a string. So I like to write a function to pretty print the Xml document for output to the Immediate window. Here is it


Option Explicit

Function PrettyPrintXml(ByVal dom As MSXML2.DOMDocument60) As String

    Dim reader As MSXML2.SAXXMLReader60
    Set reader = New MSXML2.SAXXMLReader60
    
    Dim writer As MSXML2.MXXMLWriter60
    Set writer = New MSXML2.MXXMLWriter60
    writer.omitXMLDeclaration = True
    writer.indent = True

    reader.PutProperty "http://xml.org/sax/properties/lexical-handler", writer
    
    Set reader.contentHandler = writer
    reader.Parse dom.XML
   
    PrettyPrintXml = writer.output
End Function

Private Sub TestPrettyPrintXml()

    Dim sSampleXml As String
    sSampleXml = "<note><to>Tove</to><from>Jani</from>" & _
        "<heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"

    Dim dom As MSXML2.DOMDocument60
    Set dom = New MSXML2.DOMDocument60
    dom.LoadXML sSampleXml
    Debug.Assert dom.parseError.ErrorCode = 0
    
    Dim sPrettified As String
    sPrettified = PrettyPrintXml(dom)
    
    Debug.Print sPrettified
    
    Dim vSplitLines As Variant
    vSplitLines = VBA.Split(sPrettified, vbNewLine)
    
    Debug.Assert vSplitLines(0) = ""
    Debug.Assert vSplitLines(1) = vbTab & "Tove"
    Debug.Assert vSplitLines(2) = vbTab & "Jani"
    Debug.Assert vSplitLines(3) = vbTab & "Reminder"
    Debug.Assert vSplitLines(4) = vbTab & "Don't forget me this weekend!"
    Debug.Assert vSplitLines(5) = ""
End Sub



No comments:

Post a Comment