[英]Query XML with LINQ to return child elements that are different
Consider the following two XML documents.. 考虑以下两个XML文档。
Original 原版的
<Stock>
<Vehicle id="123456">
<Name>Ford Ka</Name>
<Images>
<Image Id="111111" Url="http://somewhere.com/GetImage.aspx?ImageId=111111" LastModified="2016-05-12 13:09:00"/>
<Image Id="222222" Url="http://somewhere.com/GetImage.aspx?ImageId=222222" LastModified="2016-05-12 13:09:00"/>
</Images>
</Vehicle>
</Stock>
New 新
<Stock>
<Vehicle id="123456">
<Name>Ford Ka</Name>
<Images>
<Image Id="111111" Url="http://somewhere.com/GetImage.aspx?ImageId=111111" LastModified="2016-05-12 13:09:00"/>
<Image Id="222222" Url="http://somewhere.com/GetImage.aspx?ImageId=222222" LastModified="2016-05-13 09:00:00"/>
<Image Id="333333" Url="http://somewhere.com/GetImage.aspx?ImageId=333333" LastModified="2016-05-12 13:09:00"/>
</Images>
</Vehicle>
</Stock>
So the differences between them are... 所以它们之间的区别是...
Image Id="222222"
has changed LastModified
value. Image Id="222222"
更改了LastModified
值。 <Image>
with id="333333"
. <Image>
,其id="333333"
。 How can I use LINQ to return an XDocument
that contains the <Vehicle id>
and each <Image>
where the <Image id>
value in the new XML is not in the original XML (difference 2) OR the <Image id>
IS in the original XML BUT any of the <Image>
attribute values are different to those that in the original XML for the same Image (difference 1)? 我如何使用LINQ返回一个
XDocument
,其中包含<Vehicle id>
和每个<Image>
,其中新XML中的<Image id>
值不在原始XML中(差异2)或<Image id>
IS原始XML但<Image>
属性值是否与同一Image的原始XML中的值不同(差异1)?
The resulting XDocument
should look something like this... 产生的
XDocument
应该看起来像这样...
<Stock>
<Vehicle id="123456">
<Images>
<Image Id="222222" Url="http://somewhere.com/GetImage.aspx?ImageId=222222" LastModified="2016-05-13 09:00:00"/>
<Image Id="333333" Url="http://somewhere.com/GetImage.aspx?ImageId=333333" LastModified="2016-05-12 13:09:00"/>
</Images>
</Vehicle>
</Stock>
1] join old and new vehicles by id
attribute 1]通过
id
属性加入新旧车辆
2] find new or modified Image
s, comparing them by their string representation 2]查找新的或修改的
Image
,通过它们的字符串表示形式对其进行比较
3] select Image
s into a new Vehicle
element 3]选择
Image
进入新的Vehicle
元素
4] built resulting Stock
from Vehicle
elements 4]从
Vehicle
元素中生成结果Stock
var diff = from newVehicle in newXml.Descendants("Vehicle")
join oldVehicle in oldXml.Descendants("Vehicle")
on newVehicle.Attribute("id").Value
equals oldVehicle.Attribute("id").Value
select new XElement("Vehicle", newVehicle.Attribute("id"),
new XElement("Images",
newVehicle.Descendants("Image")
.Where(i=>!oldVehicle.Descendants("Image")
.Any(iold=>iold.ToString() == i.ToString())
)
)
);
var stock = new XElement("Stock", diff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.