如何使用Linq合并两个XElements列表?

时间:2015-07-28 10:17:13

标签: c# linq

我正在尝试合并两个XElements列表,如下所示:

list1的:

<Element name="foo">
    <ChildElement name="childFoo">
        <SubChildElement name="subChildFoo" />
    </ChildElement>
</Element>
<Element name="bar">
    <ChildElement name="childBar">
        <SubChildElement name="subChildBar" />
    </ChildElement>
</Element>
<Element name="zoo" />

列表2:

<Element name="foo" attr="fooAtr" />
<Element name="bar" attr="barAtr" />
<Element name="zoo" attr="barAtr" />

,结果应如下所示:

<Element name="foo" attr="fooAtr">
    <ChildElement name="childFoo">
        <SubChildElement name="subChildFoo" />
    </ChildElement>
</Element>
<Element name="bar" attr="barAtr">
    <ChildElement name="childBar">
        <SubChildElement name="subChildBar" />
    </ChildElement>
</Element>
<Element name="zoo" attr="barAtr" />

我尝试使用.Concat()方法,但它只是将它们加在一起:

var merged_list = list1.Concat(list2);

我想将具有相同名称属性的元素合并为一个。我怎么能用linq做到这一点?

2 个答案:

答案 0 :(得分:2)

也许连接会这样做:

 if (isset($_POST['submit'])) //this is false, your button must have a name="submit" attribute
 $file_name  = $_POST['file_name']; // you don't have any element with this name.

答案 1 :(得分:1)

您可以将list2放入字典并将属性应用于list1吗?

var doc1 = XDocument.Parse(@"
    <root>
        <Element name=""foo"">
            <ChildElement name=""childFoo"">
                <SubChildElement name=""subChildFoo"" />
            </ChildElement>
        </Element>
        <Element name=""bar"">
            <ChildElement name=""childBar"">
                <SubChildElement name=""subChildBar"" />
            </ChildElement>
        </Element>
        <Element name=""zoo"" />
    </root>");

var doc2 = XDocument.Parse(@"
    <root>
        <Element name=""foo"" attr=""fooAtr"" />
        <Element name=""bar"" attr=""barAtr"" />
        <Element name=""zoo"" attr=""barAtr"" />
    </root>");

var attributes = doc2.Descendants("Element")
    .ToDictionary(e => e.Attribute("name").Value, e => e.Attribute("attr").Value);
doc1.Descendants("Element")
    .ToList()
    .ForEach(e => e.Add(new XAttribute("attr", attributes[e.Attribute("name").Value])));
Console.WriteLine(doc1);

输出:

<root>
  <Element name="foo" attr="fooAtr">
    <ChildElement name="childFoo">
      <SubChildElement name="subChildFoo" />
    </ChildElement>
  </Element>
  <Element name="bar" attr="barAtr">
    <ChildElement name="childBar">
      <SubChildElement name="subChildBar" />
    </ChildElement>
  </Element>
  <Element name="zoo" attr="barAtr" />
</root>