如何使用Linq比较两个XDocument之间的元素?

时间:2017-08-19 15:27:26

标签: c# linq linq-to-xml

我尝试比较两个不同的XDocument中的元素,其中一些XElements在Linq中相互匹配,我还想尝试如何在“srcTree”中显示元素。那不在' srcTree2'。我曾经尝试过'其中'来自Linq,但遗憾的是没有任何运气。

我的代码如下:

class LearnXML {
    static void Main() {
        XDocument srcTree = new XDocument(
            new XComment("This is a comment"),
            new XElement("Root",
                new XElement("Child", "data1"),
                new XElement("Child", "data2"),
                new XElement("Child", "data3"),
                new XElement("Child", "data4"),
                new XElement("Info", "info5"),
                new XElement("Info", "info6"),
                new XElement("Info", "info7"),
                new XElement("Info", "info8")
            )
        );

        XDocument srcTree2 = new XDocument(
            new XComment("This is a comment"),
            new XElement("Root",
                new XElement("Child", "data1"),
                new XElement("Child", "data4"),
                new XElement("Info", "info6"),
                new XElement("Info", "info8")
            )
        );

        Console.WriteLine(srcTree);

        XDocument doc = new XDocument(
            new XComment("This is a comment"),
            new XElement("Root",
                from el in srcTree2.Element("Root").Elements()
                join rp in srcTree.Element("Root").Elements()
                on !el.Element("Child").Value equals rp.Element("Child").Value
                select el
            )
        );

        Console.WriteLine(doc);
    }
}

1 个答案:

答案 0 :(得分:1)

代码中的问题是您尝试通过相等加入两个Roots然后反转它。所以你的代码甚至都没有编译。

您可以使用嵌套查询检索两个Roots之间的差异。因此,下面的代码不仅检索所有差异节点"Child"节点。

      XDocument doc = new XDocument(
            new XComment("This is a comment"),
            new XElement("Root",
                from left in srcTree.Element("Root").Elements()
                where left != null && !(from right in srcTree2.Element("Root").Elements()
                                        where right != null
                                        select right.Value).Contains(left.Value)
                select left)
        );

如果您真的想要检索节点"Child"之间的差异,只需按名称获取元素:

        XDocument doc = new XDocument(
            new XComment("This is a comment"),
            new XElement("Root",
                from left in srcTree.Element("Root").Elements("Child")
                where left != null && !(from right in srcTree2.Element("Root").Elements("Child")
                                        where right != null
                                        select right.Value).Contains(left.Value)
                select left)
        );