2009-12-09 112 views
17

我將如何去除一個XmlDocument實例中的所有評論標籤?如何從XmlDocument中刪除所有評論標籤

是否有比檢索XmlNodeList和迭代這些更好的方法?


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

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

對我來說似乎很好。 – Dave 2009-12-09 14:15:34

回答

28

當您加載XML,可以使用XmlReaderSettings

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

在現有的情況下,您的解決方案看起來不錯。

4

沒有這個關於它,雖然我會傾向於將節點放在列表中的第一個。

我不知道有關的XmlNodeList的.NET實現,但我知道,以前的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 

它omitts文檔頂部父註釋節點,但他們可以以某種方式直接在需要時使用With xmldoc.documentElement.childNodes進行檢索,例如。

相關問題