XDocument如何评论元素

C1r*_*dec 1 c# linq-to-xml

我只想知道如何使用XDocument对整个元素进行注释.

XDocument doc = XDocument.Parse("<configuration>
      <connectionString>
          ...
      </connectionString>
<configuration>");

/*Something like that*/ doc.Root.Element("connectionStrings").NodeType = XComment; /*??*/
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

也许是这样的事情:

var element = doc.Root.Element("connectionStrings");
element.ReplaceWith(new XComment(element.ToString()));
Run Code Online (Sandbox Code Playgroud)

样本输入/输出:

之前:

<root>
  <foo>Should not be in a comment</foo>
  <connectionStrings>
    <nestedElement>Text</nestedElement>
  </connectionStrings>
  <bar>Also not in a comment</bar>
</root>
Run Code Online (Sandbox Code Playgroud)

后:

<root>
  <foo>Should not be in a comment</foo>
  <!--<connectionStrings>
  <nestedElement>Text</nestedElement>
</connectionStrings>-->
  <bar>Also not in a comment</bar>
</root>
Run Code Online (Sandbox Code Playgroud)

如果你想要添加换行符......

那是你在找什么?