Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument how can I comment an Element

Tags:

c#

linq-to-xml

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; /*??*/
like image 877
C1rdec Avatar asked Oct 21 '25 00:10

C1rdec


1 Answers

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?

like image 195
Jon Skeet Avatar answered Oct 23 '25 14:10

Jon Skeet