How to delete XML comments

后端 未结 2 908
青春惊慌失措
青春惊慌失措 2021-01-14 16:43

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 an

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 17:24

    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"
    

提交回复
热议问题