28

How would i go about to remove all comment tags from a XmlDocument instance?

Is there a better way than retrieving a XmlNodeList and iterate over those?

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

3 Answers 3

35

When you load the xml, you can use XmlReaderSettings

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

On an existing instance, your solution looks good.

Sign up to request clarification or add additional context in comments.

Comments

6

Nope thats about it, although I'd be inclind to place the nodes in a List first.

I'm not sure about the .NET implementation of XmlNodeList but I know that previous MSXML implementations loaded the list in lazy manner and code such as the above in the past would end up failing in some way as result of the DOM tree being modified as the List is enumerated.

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

Comments

0

Today looking for the way how to extract <!-- --> from Visual Basic for Applications (not C#), I have found also nodeTypeString property, but it takes more space. Here is an example in 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 

It omitts document top parent comment nodes, but they can be retrieved somehow directly if needed, for example using With xmldoc.documentElement.childNodes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.