3

I wrote a VBScript to remove all the comments in a XML file. But it didn't work correctly. The script reads from a .xml file, generates a XML file which removes comments and another temp XML file.

Set argus = WScript.Arguments
If argus.Count = 0 Then
    WScript.Quit
End If
Set fs = CreateObject("Scripting.FileSystemObject")
Set f_tu = fs.opentextfile(argus(0), 1, True)
Set f_tun = fs.opentextfile(argus(1), 2, True)
Set re_start = New RegExp
' re_start.Pattern="<!--.*-->"
re_start.Pattern="<!--"
' <!--.*|
re_start.IgnoreCase = False
re_start.Global = False
Setre_end = New RegExp
re_end.Pattern = "-->"
re_end.IgnoreCase = False
re_end.Global = False
Do While f_tu.AtEndOfStream <> True
    data = f_tu.ReadLine
    If re_start.Test(data) Then
        Do While f_tu.AtEndOfStream <> True
            data = f_tu.ReadLine
            If re_end.Test(data) Then
                Exit Do
            End If
        Loop
        MsgBox data
    Else
        dataset = dataset+1
        f_tun.WriteLine data
    End If
Loop
f_tu.Close
f_tun.Close
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Rui Lu
  • 33
  • 4

2 Answers2

2

You can try with something like

With WScript.CreateObject("msxml2.DOMDocument.6.0")
    .Async = False
    .Load "in.xml"
    .SelectNodes("//comment()").RemoveAll
    .Save "out.xml"
End With 
MC ND
  • 69,615
  • 8
  • 84
  • 126
1

Do not use string methods for manipulating XML nodes. Every time you do a kitten dies.

Use a proper XML parser, e.g. like this:

Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.Async = False
xml.Load "C:\path\to\input.xml"

If xml.ParseError <> 0 Then
  WScript.Echo xml.ParseError.Reason
  WScript.Quit 1
End If

Set comments = xml.SelectNodes("//comment()")

The above will give you a collection with the comment nodes in your XML document. After that it depends on what you want to do with the comments. If you want to remove them from the XML use something like this:

For Each comment In comments
  comment.ParentNode.RemoveChild(comment)
Next

If you want to uncomment nodes that had been commented use something like this:

Set fragment = CreateObject("Msxml2.DOMDocument.6.0")
fragment.Async = False
For Each comment In comments
  fragment.LoadXml comment.Text
  Set node = xml.ImportNode(fragment.DocumentElement, True)
  comment.ParentNode.ReplaceChild(node, comment)
Next

Then save the XML back to a file:

xml.Save "C:\path\to\output.xml"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328