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

时间:2009-12-09 14:06:52

标签: c# .net xmldocument

我将如何从XmlDocument实例中删除所有注释标记?

有没有比检索XmlNodeList更好的方法并迭代这些?


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

    foreach(XmlNode node in list)
    {
        node.ParentNode.RemoveChild(node);
    }

3 个答案:

答案 0 :(得分:28)

加载xml时,可以使用XmlReaderSettings

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

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

答案 1 :(得分:5)

不管怎么说,虽然我会先将节点放在List中。

我不确定XmlNodeList的.NET实现,但我知道之前的MSXML实现以惰性方式加载列表,过去上面的代码最终会以某种方式失败作为结果在枚举List时修改DOM树。

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

答案 2 :(得分: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