1

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?

3
  • Look at this link. Its a similar question: stackoverflow.com/questions/12783525/… Commented Dec 23, 2013 at 11:36
  • Thanks, but the critical difference is that I need to insert it at the start of the root element. The root element (in XML) has no name, and does Add not put it at the end of the element? I need it to be at the start of the root element. Commented Dec 23, 2013 at 11:50
  • How about using doc.AddFirst(comment), assuming doc is the XDocument and comment is the XComment object you have? I didn't see any drawback with that.. Commented Dec 23, 2013 at 11:52

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. Thanks all three. I didn't notice the AddFirst method
1

You can use doc.Element("stock").AddFirst

and as mentioned in the comment section look at add data to existing xml file using linq

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.