简体   繁体   中英

Insert XComment before node using Linq to XML

I need to insert a xml comment XComment right above each node. It is the same as this question Using XPath to access comments a flat hierachy . What would be the eqivalent of //comment()[following-sibling::*[1][self::attribute]] in Linq?

A use case for me would be like this:

<root>
 <node id="1">
  <element>test</element>
 </node>
 <!-- comment here: TODO: check if ok -->
 <node id="2">
  <element>is this ok?</element>
 </node>
</root>

Sorry, there seems to be a misunderstanding. I have a xml file and need to add a XComment after I select a node using Linq and lambda expression. That means I load a xml, select a node under root and add XComment.

var doc = new XDocument(
            new XElement("root",
                new XElement("node",
                    new XComment("comment here: TODO: check if ok"),
                    new XElement("element", "is this ok?")
                    )
                )
            );

I guess you are reading an existing file and want to add the comments there, so this should work for you:

var xdoc = XDocument.Load("//path/to/file.xml");
var nodes = xdoc.XPathSelectElements("//node");
foreach (var n in nodes)
{
    n.AddBeforeSelf(new XComment("This is your comment"));
}

If you have to use LINQ and not XPath for some reason, use this:

var nodes = xdoc.Descendants().Where(n=>n.Name=="node");
foreach (var n in nodes)
{
    n.AddBeforeSelf(new XComment("This is your comment"));
}

Try this:-

XDocument xdoc = XDocument.Load(@"YourXMl.xml");
xdoc.Descendants("node").FirstOrDefault(x => (string)x.Attribute("id") == "2")
                        .AddBeforeSelf(new XComment("comment here: TODO: check if ok"));
xdoc.Save(@"YourXML.xml");

Here, in the filter clause you need to pass the condition before which you wish to add your comments. Please notice since I have used FirstOrDefault , you may get null reference exception in case of no match, thus you'll have to check for nulls before adding the comments.

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