【问题标题】:How do I insert an element into XML using Linq?如何使用 Linq 将元素插入 XML?
【发布时间】:2010-01-25 08:35:45
【问题描述】:

我的 XML:

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

我已经使用类似于以下的 XML 加载了它:

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

我想插入另一个元素,结果如下:

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

如何使用 Linq2Xml 做到这一点?

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

    试试这个:

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

    或者,如果你像我一样喜欢 XPath:

    xDoc.XPathSelectElement("content/item[@id = '2']")
        .AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));
    

    【讨论】:

    • 太棒了!谢谢 :) 我现在唯一的问题是 XPathSelectElement 在哪里?我似乎在我正在使用的任何命名空间中都找不到它。 (我正在使用 System.Linq 和 System.Xml.Linq)
    • XPathSelectElement 在 System.Xml.XPath 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多