如何将两个XElement与linq select结合? [英] How do I combine two XElements with linq select?

查看:64
本文介绍了如何将两个XElement与linq select结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个XElement列表合并为一个:

I'm trying to combine two lists of XElements into one :

var list1 = XElement.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>").XPathSelectElements("Element").ToList();

var list2 = XElement.Parse(@"<root><Element name=""foo"" attr=""fooAtr"" />
                                    <Element name=""bar"" attr=""barAtr"" />
                                    <Element name=""zoo"" attr=""barAtr"" /></root>").XPathSelectElements("Element").ToList();

var res = from e2 in list2
           join e1 in list1
           on e2.Attribute("name").Value equals e1.Attribute("name").Value
           select new XElement(e1.Add(e2.Element("ChildElement")));

由于选择错误(XElement.Add()返回void),因此代码无法编译.

The code won't compile because the select is wrong (XElement.Add() returns void).

如何在select中合并两个XElement:e1和e2并返回新的xelement(e2和e1中的子元素)

How can I combine the two XElements : e1 and e2 inside the select and return the new xelement (e2 with the subelement from e1)

我要获取以下格式的列表:

I want to obtain a list in this format :

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

推荐答案

我将放弃XPath并使用LINQ to XML查询方法来查找您的元素.您的select需要从第二个元素复制名称和属性,并从第一个元素复制子元素:

I would ditch the XPath and use the LINQ to XML query methods to find your elements. Your select needs to copy the name and attributes from the second element and the child elements from the first:

var results = from e2 in second.Descendants("Element")
              join e1 in first.Descendants("Element")
                  on (string)e2.Attribute("name") equals (string)e1.Attribute("name")
              select new XElement(e2.Name, e2.Attributes(), e1.Elements());

在此处查看有效的演示: https://dotnetfiddle.net/J3mcXu

See a working demo here: https://dotnetfiddle.net/J3mcXu

这篇关于如何将两个XElement与linq select结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆