views:

375

answers:

3

I've recently have a reason to include into our build script the creation of an XML configuration file. The most straightforward way I can think of to do this is to hard-code the XML content as a string into the script and then to simply create a file and write that XML string to the file (named appropriately etc). Is there a more elegant or efficient way of doing this?

The build script that I am looking to modify is written in VBScript.

A: 

Very important read if you consider strings: HOWTO Avoid Being Called a Bozo When Producing XML

stesch
+1  A: 

Hi,

you could use an XmlWriter to avoid printing strings. This will make writing well-formed XML documents a lot easier.

You can find free sample code in VBScript here

http://www.matthewflickinger.com/lab/xmlwriter/

0xA3
A: 

My final solution: adapted the XMLWriter mentioned by divo (used it pretty much as is, apart from one or two changes since this script is to run on the client). Also adapted the code from here to pretty-print the XML (so that it can be readable when output to file):

Function XMLToString(Nodes)
  dim retStr
  retStr = "<?xml version=""1.0"" encoding=""utf-8"" ?>"
  XMLToString = retStr & vbNewLine & NodesToString(Nodes, 0)
End Function

Function NodesToString(Nodes, Indent)
   Dim xNode
   Dim retStr

   retStr = ""
   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
            retStr = retStr & VBNewLine & strDup(" ", Indent)  & "<" & xNode.nodeName & AttributesToString(xNode) & ">"
            If xNode.hasChildNodes Then
              retStr = retStr & NodesToString(xNode.childNodes, Indent + 2)
            End If
            retStr = retStr & VBNewLine & strDup(" ", Indent) & "</" & xNode.nodeName & ">"
          Else 
            If xNode.hasChildNodes Then
              retStr = retStr & NodesToString(xNode.childNodes, Indent + 2)
            End If
          End If
        Case 3:   ' NODE_TEXT                       
          retStr = retStr & VBNewLine & strDup(" ", Indent) & xNode.nodeValue
      End Select
   Next

   NodesToString = retStr
End Function

Function AttributesToString(Node)
   Dim xAttr, res

   res = ""
   For Each xAttr In Node.attributes
        res = res & " " & xAttr.name & "=""" & xAttr.value & """"
   Next

   AttributesToString = res
End Function

Function strDup(dup, c)
  Dim res, i

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