Forcing MSXML to format XML output with indents and newlines

前端 未结 4 517
不思量自难忘°
不思量自难忘° 2021-01-01 04:40

I am using MSXML 3.0 with Visual Basic 6 to store and retrieve configuration of my application. When saving the resulting DOMDocument to a XML file the root obj

4条回答
  •  灰色年华
    2021-01-01 05:21

    Here is a shorter indentation utility function that works on DOM objects and strings as input and outputs a formatted string. File handling (utf-8) is left outside its scope. Does not use ADODB streams and does not need MSXML in project references.

    Public Function FormatXmlIndent(vDomOrString As Variant, sResult As String) As Boolean
        Dim oWriter         As Object ' MSXML2.MXXMLWriter
    
        On Error GoTo QH
        Set oWriter = CreateObject("MSXML2.MXXMLWriter")
        oWriter.omitXMLDeclaration = True
        oWriter.indent = True
        With CreateObject("MSXML2.SAXXMLReader")
            Set .contentHandler = oWriter
            '--- keep CDATA elements
            .putProperty "http://xml.org/sax/properties/lexical-handler", oWriter 
            .parse vDomOrString
        End With
        sResult = oWriter.output
        '--- success
        FormatXmlIndent = True
        Exit Function
    QH:
    End Function
    

    Can be used like this

        sXml = ReadTextFile("doc.xml")
        FormatXmlIndent sXml, sXml
    

    ... so if anything fails (invalid XML, etc.) sXml still holds original unformatted input.

提交回复
热议问题