How to Generate a well formatted XML file using VB 6.0?

vb6, xml

Solution

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.

Problem

I'm working on Visual Basic 6.0 Project and i need to generate a well formatted XML file whose looks like this: ``` <Myinfo> <FirstName>My First Name</FirstName> <LastName>My Last Name</LastName> <StreetAdd>My Address</StreetAdd> <MyInfo> ``` Note: i got the job done generating the XML file, but i'm still in need for the right formatting as shown above. The XML file i generated is formatted like in one single line like this: ``` <Myinfo><FirstName>My First Name</FirstName><LastName>My Last Name</LastName><StreetAdd>My Address</StreetAdd><MyInfo> . ```

Original source

Related problems