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

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

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

XmlNodeList list = xmlDoc.SelectNodes("//comment()"); foreach(XmlNode node in list) { node.ParentNode.RemoveChild(node); } 

加载xml时,可以使用XmlReaderSettings

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

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

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

我不确定XmlNodeList的.NET实现,但我知道以前的MSXML实现以惰性方式加载列表,并且过去的代码如上所述会因为DOM树被修改为某种方式而失败。列表是枚举的。

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

今天寻找如何从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