XDocument how can I comment an Element

c#, linq-to-xml

Solution

Something like this, perhaps:

var element = doc.Root.Element("connectionStrings");
element.ReplaceWith(new XComment(element.ToString()));

Sample input/output:

Before:

<root>
  <foo>Should not be in a comment</foo>
  <connectionStrings>
    <nestedElement>Text</nestedElement>
  </connectionStrings>
  <bar>Also not in a comment</bar>
</root>

After:

<root>
  <foo>Should not be in a comment</foo>
  <!--<connectionStrings>
  <nestedElement>Text</nestedElement>
</connectionStrings>-->
  <bar>Also not in a comment</bar>
</root>

Add line breaks if you want to...

Is that what you were looking for?

Problem

I just want to know how I can comment an entire element using XDocument. ``` XDocument doc = XDocument.Parse("<configuration> <connectionString> ... </connectionString> <configuration>"); /*Something like that*/ doc.Root.Element("connectionStrings").NodeType = XComment; /*??*/ ```

Original source