如何删除XML注释

时间:2016-09-21 06:57:41

标签: xml vbscript

我写了一个VBScript来删除XML文件中的所有注释。但它无法正常工作。该脚本从.xml文件读取,生成一个XML文件,用于删除注释和另一个临时XML文件。

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

2 个答案:

答案 0 :(得分:2)

您可以尝试使用类似

的内容
With WScript.CreateObject("msxml2.DOMDocument.6.0")
    .Async = False
    .Load "in.xml"
    .SelectNodes("//comment()").RemoveAll
    .Save "out.xml"
End With 

答案 1 :(得分:1)

使用字符串方法来操作XML节点。每当你做一只小猫死亡。

使用适当的XML解析器,例如像这样:

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()")

上面的内容将为您提供XML文档中带有注释节点的集合。之后,这取决于你想要对评论做什么。如果要从XML中删除它们,请使用以下内容:

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

如果要取消注释已注释的节点,请使用以下内容:

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

然后将XML保存回文件:

xml.Save "C:\path\to\output.xml"
相关问题