如何从XmlDocument中删除所有的注释标签

28
我该如何从一个XmlDocument实例中删除所有注释标签?是否有更好的方法,而不是检索XmlNodeList并对其进行迭代?

    XmlNodeList list = xmlDoc.SelectNodes("//comment()");

    foreach(XmlNode node in list)
    {
        node.ParentNode.RemoveChild(node);
    }
3个回答

35

当您加载xml时,您可以使用XmlReaderSettings

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create("...", settings);
xmlDoc.Load(reader);

在现有实例上,您的解决方案看起来很不错。


6

就这些内容,不过我倾向于先将节点放入一个列表中。

我不确定.NET实现的XmlNodeList,但我知道以前的MSXML实现是以惰性方式加载列表的,因此像上面的代码一样,在枚举列表时由于DOM树被修改而导致某些方式失败。

 foreach (var node in xml.SelectNodes("//comment()").ToList())
   node.ParentNode.RemoveChild(node);

0
今天在寻找从Visual Basic for Applications(而不是C#)中提取<!-- -->的方法时,我还发现了nodeTypeString属性,但它需要更多的空间。以下是VBA示例:
Dim xmldoc As New MSXML2.DOMDocument30
Dim oNodeList As IXMLDOMSelection
Dim node As IXMLDOMNode
Dim i As Long

Dim FileName As String, FileName1 As String

FileName = "..." ' Source
FileName2 = "..." ' Target

xmldoc.async = False ' ?
xmldoc.Load FileName
If (xmldoc.parseError.errorCode <> 0) Then Exit Sub ' or Function

Set oNodeList = xmldoc.selectNodes("//*") '' all nodes

For i = 0 To oNodeList.length - 1
With oNodeList(i)

     For Each node In .childNodes
         If node.nodeTypeString = "comment" Then .removeChild node
     Next

End With
Next

xmldoc.Save FileName2

Set oNodeList = Nothing ' ?
Set xmldoc = Nothing

它省略了文档顶级父评论节点,但如果需要,可以直接使用With xmldoc.documentElement.childNodes来检索它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接