XDocument如何对元素进行注释?

3
我想知道如何使用XDocument注释整个元素。
XDocument doc = XDocument.Parse("<configuration>
      <connectionString>
          ...
      </connectionString>
<configuration>");

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

8
也许是这样的内容:

类似这样的东西:

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>

如果你想在文本中添加换行符,可以使用<br>标签。

这就是你要找的内容吗?


可恶的 Skeet!我正在写同样的东西,但是你来了,写得更快更好。哈哈,+1! - Tim S.
我想要所有子节点都在注释中。替换全部吗? - C1rdec
@Cedric:它们已经在注释部分内了。(如果您列出上面的所有后代元素,它不会显示“nestedElement”。) - Jon Skeet

0

如果有人想知道如何实现多行:

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")}")));
}

结果:

Resulting Xml construct


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接