如何在XDocument中放入Linq变量

本文关键字:Linq 变量 XDocument | 更新日期: 2023-09-27 18:00:57

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

(还有给Gert Jan的thnx,他为我提供了部分代码(

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

如何在XDocument中放入Linq变量

您正试图向文档的绝对根添加几个元素,并给出几个根元素。

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

newXdoc.Root.Add(cComb);

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