Search code examples
c#linq-to-xmlxelement

How to Convert XElement to XComment (C#)


My first question here...

I'm parsing 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 besides parsing it as a text file.

Result should look like this:

<EnabledElement>ABC</EnabledElement>
<!-- DisabledElement></DisabledElement-->

Solution

  • Well it's not quite as you were asking for, but this does replace an element with a commented version:

    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 the comment opening and closing < and > to replace the ones from the element, you can use:

    value2.ReplaceWith(new XComment(value2.ToString().Trim('<', '>')));
    

    ... but I personally wouldn't.