简体   繁体   English

如何使用Linq在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. 我需要在现有xml文件的开头(即在根目录中)插入XML注释,以便用户在文本编辑器中查看它。

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? Assunming我已经将文件读入XDocument对象并创建了一个新的XComment对象,使用Linq to XML,在根元素的开头注入这个的推荐方法是什么?

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. 就在?xml声明下。

You can use doc.Element("stock").AddFirst 您可以使用doc.Element(“stock”)。AddFirst

and as mentioned in the comment section look at add data to existing xml file using linq 并且如评论部分所述,查看使用linq将数据添加到现有xml文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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