简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM