如何将Linq var放入XDocument?

时间:2011-06-30 07:42:23

标签: c# xml linq linq-to-xml

我有以下代码,但它不起作用。我怎样才能做到这一点? 以下代码给出了一个例外: newXdoc.Add(cComb); 此操作会创建结构不正确的文档。

(对于Gert-Jan而言,他也部分为我提供了代码)

private void button1_Click(object sender, EventArgs e)
{
    var x1 = XDocument.Load(sourceFilepathTb.Text);
    var x2 = XDocument.Load(targetFilepathTb.Text);

    // select the CLASS nodes from each
    var c1 = x1.Descendants("ActionDesign").First().Descendants("Action");
    var c2 = x2.Descendants("ActionDesign").First().Descendants("Action");

    // this one gives the distinct union of the two, you can 
    // put that into the result xdoc.
    var cComb =
        c1
        .Union(c2)
        .Distinct(new ClassComparer())
        .OrderBy(c => c.Attribute("Id").Value);

    XDocument newXdoc = new XDocument(
        new XDeclaration("1", "utf-8", null),
        new XElement("Application"));
    //newXdoc.Add(new XElement(cComb));
    //newXdoc.Add(new XDeclaration("1", "utf-8", "yes"));
    newXdoc.Add(cComb);

1 个答案:

答案 0 :(得分:2)

您正在尝试向文档的绝对根添加多个元素,并提供多个根元素。

解决此问题的最简单方法就是使用:

newXdoc.Root.Add(cComb);

这会将元素添加到现有的根元素中。

相关问题