2014-05-23 55 views
0

我只想知道如何使用XDocument评论整个元素。XDocument如何评论元素

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

/*Something like that*/ doc.Root.Element("connectionStrings").NodeType = XComment; /*??*/ 

回答

5

事情是这样的,也许:

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

样品输入/输出:

前:

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

后:

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

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

这就是您要找的内容吗?

+0

诅咒你,Skeet!我写的是同样的东西,但是后来你写得更快更好。哈哈,+1! –

+0

我想要所有的子节点都在注释全部替换? – C1rdec

+0

@Cedric:他们已经是 - 全都在评论部分。 (如果你列出了上面所有的后代元素,它*不会显示'nestedElement'。) –