[英]How to remove all comment tags from 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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.