Linq加入XML

时间:2017-11-02 16:54:50

标签: c# xml linq

我有两个xmls文件,我想使用Linq在它们上面进行查询。我可以使用XDocument进行简单查询,但知道我正在尝试通过特定元素构建连接,例如:DE2002。这些是xmls文件的示例。有什么建议吗?

SELECT total AS Registrations, date AS `Creation Date`, @running_count := @running_count + total AS Accumulated
FROM (
    SELECT date(created_at) AS date, COUNT(*) AS total
    FROM Users
    GROUP BY date
    ORDER BY date) AS u
CROSS JOIN (SELECT @running_count := 0) AS var

1 个答案:

答案 0 :(得分:0)

您可以像这样加入他们:

XElement list1 =
new XElement("DataBase",
    new XElement("Record",
        new XAttribute("RecordType", "4"),
        new XElement("DE1017", "245254"),
        new XElement("DE1021", "2435234525"),
        new XElement("DE2002", "65456464")),
    new XElement("Record",
        new XAttribute("RecordType", "4"),
        new XElement("DE1017", "245245"),
        new XElement("DE1021", "24525442"),
        new XElement("DE2002", "56464")));

XElement list2 =
new XElement("DataBase",
    new XElement("Record",
        new XAttribute("RecordType", "4"),
        new XElement("DE1017", "245245"),
        new XElement("DE1021", "23434"),
        new XElement("DE2002", "65456464")),
    new XElement("Record",
        new XAttribute("RecordType", "4"),
        new XElement("DE1017", "23452345"),
        new XElement("DE1021", "24525va2345234523lue2442"),
        new XElement("DE2002", "56464")));

var query = list1.Descendants("Record").Join(list2.Descendants("Record"),
                                 o => o.Descendants("DE2002").First().Value,
                                 i => i.Descendants("DE2002").First().Value,
                                 (o, i) => new { List1 = o, List2 = i });

使用每个Value中第一个DE2002元素中的Record加入它们。对于每个匹配,都会创建一个新的匿名对象,其中包含List1List2属性,从匹配的行中填充。

如果您使用“真实”类(从XML填充而不是直接从XML数据源填充),这将会非常容易。

LINQPad文件可用here

这会产生2个结果“行”,如下所示:

enter image description here