Dim*_*rba 3 c# xelement linq-to-xml
我的第一个问题是...
我正在解析 xml 文件(使用 c# 作为 Xdocument)并尝试禁用一些 xElement 对象。标准方法(我工作的地方)是让它们显示为 xComment。
除了将其解析为文本文件之外,我找不到任何方法来执行此操作。
结果应该是这样的:
<EnabledElement>ABC</EnabledElement>
<!-- DisabledElement></DisabledElement-->
Run Code Online (Sandbox Code Playgroud)
嗯,它并不完全符合您的要求,但这确实用注释版本替换了元素:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
<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>
Run Code Online (Sandbox Code Playgroud)
如果您确实想要注释的打开和关闭<并>替换元素中的注释,您可以使用:
value2.ReplaceWith(new XComment(value2.ToString().Trim('<', '>')));
Run Code Online (Sandbox Code Playgroud)
...但我个人不会。