9

My XML:

<content>
    <item id="1">A</item>
    <item id="2">B</item>
    <item id="4">D</item>
</content>

I have loaded this using XML similar to:

XDocument xDoc = new XDocument(data.Value);
var items = from i in xDoc.Element("content").Elements("item")
    select i;

I want to insert another element, to end up with something like:

<content>
    <item id="1">A</item>
    <item id="2">B</item>
    <item id="3">C</item>
    <item id="4">D</item>
</content>

How do I do this using Linq2Xml?

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
Matt W
  • 11,753
  • 25
  • 118
  • 215

1 Answers1

22

Try this:

xDoc.Element("content")
    .Elements("item")
    .Where(item => item.Attribute("id").Value == "2").FirstOrDefault()
    .AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));

Or, if you like XPath like I do:

xDoc.XPathSelectElement("content/item[@id = '2']")
    .AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • 2
    Fantastic! Thank you :) My only question now is where is the XPathSelectElement? I can't seem to find it in any of the namespaces I'm using. (I'm using System.Linq and System.Xml.Linq) – Matt W Jan 25 '10 at 12:01
  • XPathSelectElement is in System.Xml.XPath – majjam Mar 01 '22 at 15:17