我将如何从 XmlDocument 实例中删除所有评论标签?
有没有比检索 XmlNodeList 并遍历它们更好的方法?
XmlNodeList list = xmlDoc.SelectNodes("//comment()");
foreach(XmlNode node in list)
{
node.ParentNode.RemoveChild(node);
}
我将如何从 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);
在现有实例上,您的解决方案看起来不错。
不,就是这样,尽管我倾向于先将节点放在列表中。
我不确定 .NET 的实现,XmlNodeList
但我知道以前的 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
.