我只是想知道如何使用 XDocument 注释整个元素。
XDocument doc = XDocument.Parse("<configuration>
<connectionString>
...
</connectionString>
<configuration>");
/*Something like that*/ doc.Root.Element("connectionStrings").NodeType = XComment; /*??*/
也许是这样的:
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>
如果需要,请添加换行符...
这就是您要找的吗?
如果有人想知道如何进行多行:
public static class Extensions
{
internal static void AddMultilineComment(this XDocument xDoc, string[] lines)
{
var builder = new List<string> { Environment.NewLine };
builder.AddRange(lines);
builder.Add(Environment.NewLine);
xDoc.Add(new XComment(string.Join(Environment.NewLine, builder)));
}
}
用途:
[TestMethod]
public void TryIt()
{
var xDoc = new XDocument();
xDoc.AddMultilineComment(
new string[]
{
"This excellent post answered my original ",
"question, so then it seemed like a handy",
"thing to write a multiline extension!",
});
xDoc.Add(
new XElement("connectionString",
new XAttribute("uri", $"{new Uri("https://www.ivsoftware.com")}")));
}
结果: