如何将XElement转换为XComment(C#)

3

这是我的第一个问题...

我正在解析xml文件(使用C#的Xdocument),并试图禁用一些xElement对象。在我所在的公司,标准做法是将它们显示为xComment。

除了将其解析为文本文件之外,我找不到其他方法来实现这一点。

结果应该如下所示:

<EnabledElement>ABC</EnabledElement>
<!-- DisabledElement></DisabledElement-->
1个回答

5

虽然不完全符合您的要求,但这可以用注释版本替换元素:

using System;
using System.Xml.Linq; 

public class Test
{
    static void Main()
    {
        var doc = new XDocument(
            new XElement("root",
                new XElement("value1", "This is a value"),
                new XElement("value2", "This is another value")));

        Console.WriteLine(doc);

        XElement value2 = doc.Root.Element("value2");
        value2.ReplaceWith(new XComment(value2.ToString()));
        Console.WriteLine(doc);
    }
}

输出:

<root>
  <value1>This is a value</value1>
  <value2>This is another value</value2>
</root>

<root>
  <value1>This is a value</value1>
  <!--<value2>This is another value</value2>-->
</root>

如果您真的想让注释标签的开头和结尾<以及>替换掉元素本身的标签,可以使用以下代码:
value2.ReplaceWith(new XComment(value2.ToString().Trim('<', '>')));

...但我个人不会这样做。


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