Tomalak 的代码有一点改进,我在标签末尾添加了一个 vbNewLine:
Private Sub FormatOuterXml(ByRef Parent As IXMLDOMNode, Optional ByVal Lvl As Long = 0)
If Parent.ParentNode Is Nothing Or Parent.ChildNodes.Length = 0 Then Exit Sub
Dim xn0 As IXMLDOMNode, id0 As IXMLDOMText, id1 As IXMLDOMText
Set id0 = Parent.OwnerDocument.createTextNode(vbNewLine & String(Lvl, vbTab))
If Lvl > 0 Then Set id1 = Parent.OwnerDocument.createTextNode(vbNewLine & String(Lvl - 1, vbTab))
For Each xn0 In Parent.ChildNodes
If xn0.NodeType = MSXML2.NODE_TEXT Then
If LenB(xn0.Text) = 0 Then Parent.RemoveChild xn0
ElseIf xn0.PreviousSibling Is Nothing Then
Parent.InsertBefore id0.CloneNode(True), xn0
ElseIf xn0.PreviousSibling.NodeType <> MSXML2.NODE_TEXT Then
Parent.InsertBefore id0.CloneNode(True), xn0
ElseIf xn0.NextSibling Is Nothing Then
If Not id1 Is Nothing Then Parent.appendChild id1.CloneNode(True)
End If
Next xn0
If Parent.ChildNodes.Length > 0 Then
For Each xn0 In Parent.ChildNodes
If xn0.NodeType <> MSXML2.NODE_TEXT Then FormatOuterXml xn0, Lvl + 1
Next xn0
End If
End Sub