1

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.

Community
  • 1
  • 1
sceiler
  • 1,145
  • 2
  • 20
  • 35

3 Answers3

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

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"));
}
ChriPf
  • 2,700
  • 1
  • 23
  • 25
1

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.

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56