如何在xdocument1和xdocument2之间找到区别

时间:2015-05-08 15:57:56

标签: c# xml linq-to-xml

我想在xdocument1和xdocument2之间找到区别。 在xdocument1上:

<prices>
   <price>
     <productid>P001</productid>
     <price>1000</price>
     <effectivedate>2015-05-11T00:00:00+7</effectivedate>
   </price>
</prices>

和xdocument2:

<prices>
   <price>
     <productid>P001</productid>
     <price>870</price>
     <effectivedate>2015-05-11T00:00:00+7</effectivedate>
   </price>
</prices>

如何获得它们之间的区别,如果effectivedate和productid具有相同的值,那么它应该不返回价格记录,如下所示:

<prices/>

如果有效日期不同,如下:

xdocument1上的

<prices>
   <price>
     <productid>P001</productid>
     <price>1000</price>
     <effectivedate>2015-05-12T00:00:00+7</effectivedate>
   </price>
</prices>

和xdocument2:

<prices>
   <price>
     <productid>P001</productid>
     <price>870</price>
     <effectivedate>2015-05-11T00:00:00+7</effectivedate>
   </price>
</prices>

然后价格标签应该来自xdocument1,返回:

<prices>
   <price>
     <productid>P001</productid>
     <price>1000</price>
     <effectivedate>2015-05-12T00:00:00+7</effectivedate>
   </price>
</prices>

2 个答案:

答案 0 :(得分:1)

这似乎可以按照您的意愿使用。

var query =
    new XDocument(
        new XElement(
            "prices",
            from p1 in xdocument1.Root.Elements("price")
            join p2 in xdocument2.Root.Elements("price")
                on p1.Element("productid").Value equals p2.Element("productid").Value
            where p1.Element("effectivedate").Value != p2.Element("effectivedate").Value
            select p1));

看起来很简单所以如果我错过了什么,请告诉我。

答案 1 :(得分:0)

我想建议以下步骤

  1. 将带有 ProductID 的hashmap用作包含 effectivedate price 的键和对象。
  2. 对象可以使用重写等于有效比较的方法。
  3. 首先在hashmap中加载任一文档,然后检查第二个文档的相似性或差异,并相应地返回结果。
  4. 这需要线性时间O(n + m),其中n是第一个doc的元素的大小/数量,m是第二个doc的元素的大小/数量,以找到所有的差异。
  5. 我更像是一个java人。我可以在某个时候用Java提供代码片段。