Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert an element into XML using Linq?

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?

like image 468
Matt W Avatar asked Jan 25 '10 08:01

Matt W


People also ask

Does LINQ work with XML?

The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes.

How do I add XAttribute to XElement?

XElement myelement = new XElement("myelement"); myelement. Add(new XAttribute("attributename", "attributevalue"); Console. WriteLine(myelement);

What is System XML LINQ?

LINQ to XML is an in-memory XML programming interface that enables you to modify XML documents efficiently and easily.


1 Answers

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")));
like image 65
Rubens Farias Avatar answered Nov 04 '22 22:11

Rubens Farias