How to convert XElement to XComment (C #)
My first question is here ...
I am parsing an xml file (using C # as Xdocument) and trying to disable some xElement objects. the standard way (where I work) is to make them appear as xComment.
I couldn't find any way to do this, other than parse it as a text file.
The result should look like this:
<EnabledElement>ABC</EnabledElement>
<!-- DisabledElement></DisabledElement-->
+3
source to share
1 answer
Well, it doesn't quite work as you asked, but this replaces the commented element:
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);
}
}
Output:
<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>
If you really want to open and close comments <
and >
replace items from an element, you can use:
value2.ReplaceWith(new XComment(value2.ToString().Trim('<', '>')));
... but I personally didn't.
+4
source to share