开发者

How do I insert an element into XML using Linq?

开发者 https://www.devze.com 2022-12-17 20:29 出处:网络
My XML: <content> <item id=\"1\">A</item> <item id=\"2\">B</item> <item id=\"4\">D</item>

My XML:

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

I have loaded th开发者_JAVA百科is 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?


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")));
0

精彩评论

暂无评论...
验证码 换一张
取 消