Search code examples
c#linq-to-xml

How to insert a comment in XML file using Linq


I need to insert an XML comment right at the beginning of an existing xml file (ie in the root) for users to see when they look at it in a text editor.

Basically I want to end up with something like this at the beginning...

<?xml version="1.0" encoding="utf-8"?>
<!--Don't mess with this file -->
....

Assunming I have read the file into an XDocument object and created a new XComment object, using Linq to XML what's the recommended approach to inject this at the start of the root element?


Solution

  • There is a simple method for that:

    XDocument doc = ...;
    doc.AddFirst(new XComment("Don't mess with this file"));
    

    This will place the comment above and outside the root element. Just under the ?xml declaration.