VBScript XML pretty print

  • : Function split() is deprecated in /hsphere/local/home/guruj/guruj.net/modules/filter/filter.module on line 1200.
  • : Function split() is deprecated in /hsphere/local/home/guruj/guruj.net/modules/filter/filter.module on line 1200.

I don't know if this would ever be useful to anyone, but anyway:

Option Explicit

Dim xmlDoc
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
xmlDoc.loadXML("<GetList><a><b attr=""5"">a node</b></a></GetList>")

DisplayNode xmlDoc.childNodes


' =================== Helper Routines ==================

Sub DisplayNode(Nodes)
  DisplayNode_ Nodes, 0
End Sub

Sub DisplayNode_(Nodes, Indent)
   Dim xNode
   For Each xNode In Nodes
      Select Case xNode.nodeType
        Case 1:   ' NODE_ELEMENT
          If xNode.nodeName <> "#document" Then
            ' change DisplayAttrs_(xNode, Indent + 2) to 
            ' DisplayAttrs_(xNode, 0) for inline attributes
            WScript.Echo strDup(" ", Indent)  & "<" & xNode.nodeName & _
              DisplayAttrs_(xNode, Indent + 2) & ">"
            If xNode.hasChildNodes Then
              DisplayNode_ xNode.childNodes, Indent + 2
            End If
            WScript.Echo strDup(" ", Indent) & "</" & xNode.nodeName & ">"
          Else 
            If xNode.hasChildNodes Then
              DisplayNode_ xNode.childNodes, Indent + 2
            End If
          End If
        Case 3:   ' NODE_TEXT                       
          WScript.Echo strDup(" ", Indent) & xNode.nodeValue
      End Select
   Next
End Sub

Function DisplayAttrs_(Node, Indent)
   Dim xAttr, res

   res = ""
   For Each xAttr In Node.attributes
      If Indent = 0 Then
        res = res & " " & xAttr.name & "=""" & xAttr.value & """"
      Else 
        res = res & vbCrLf & strDup(" ", Indent) & xAttr.name & _
          "=""" & xAttr.value & """"
      End If
   Next

   DisplayAttrs_ = res
End Function

Function strDup(dup, c)
  Dim res, i

  res = ""
  For i = 1 To c
    res = res & dup
  Next
  strDup = res
End Function

Comments

Useful

Twas useful to me! Many thanks