我在字符串中有以下XML。我向Web服务发送了一个请求,他们向我返回了一个XmlNode。我现在有xmlNode.InnerXml,它是下面的XML:
<Response>
<Vehicle>
...
</Vehicle>
<Premiums>
<Premium>
<ID>78601</ID>
<Name>Premium I</Name>
<Desc>Description I</Desc>
<Surcharges>
<Surcharge>
<SurchargeID>20</SurchargeID>
<SurchargeAmount>50.00</SurchargeAmount>
<SurchargeSelected>TRUE</SurchargeSelected>
</Surcharge>
</Surcharges>
</Premium>
<Premium>
<ID>78598</ID>
<Name>Premium II</Name>
<Desc>Description II</Desc>
<Surcharges>
<Surcharge>
<SurchargeID>15</SurchargeID>
<SurchargeAmount>25.00</SurchargeAmount>
<SurchargeSelected>FALSE</SurchargeSelected>
</Surcharge>
<Surcharge>
<SurchargeID>20</SurchargeID>
<SurchargeAmount>50.00</SurchargeAmount>
<SurchargeSelected>TRUE</SurchargeSelected>
</Surcharge>
</Surcharges>
</Premium>
</Premiums>
</Response>
我需要XML中的 DISTINCT 附加费。
例如:
假设:
我们还假设具有相同ID的任何附加费将始终具有相同的SurchargeAmount
和SurchargeSelected
个值。例如, 从不 是ID为20的两个附加费FALSE
和TRUE
SurchargeSelected
。
到目前为止我有什么:
XmlNode xml = GetPremiumsResponse.GetPremiumsResult;
string xmlString = xml.InnerXml;
XDocument xDoc = XDocument.Parse(xmlString);
var _premiumsList = (from r in xDoc.Descendants("Response")
from p in r.Elements("Premiums")
select p).ToList();
提前感谢任何可以帮助我的人!! :)
答案 0 :(得分:2)
var xDoc = XDocument.Parse(xmlString);
var surcharges = xDoc.Descendants("Surcharge")
.GroupBy(s => s.Element("SurchargeID").Value)
.Select(g => g.First())
.ToList();
答案 1 :(得分:1)
在XPath的帮助下:
var _premiumsList = (from s in xDoc.XPathSelectElements("/Response/Premiums/Premium/Surcharges/Surcharge")
select new
{
ID = (int)s.Element("SurchargeID"),
Amount = (decimal)s.Element("SurchargeAmount"),
Selected = (bool)s.Element("SurchargeSelected")
}).Distinct().ToList();
需要文件顶部的using System.Xml.XPath
。
它使用的事实是,匿名类型默认定义了Equals
和GetHashCode
:
因为匿名类型上的
来自Anonymous Types (C# Programming Guide) 的Equals
和GetHashCode
方法是根据属性的Equals
和GetHashcode
方法定义的,所以同一个匿名类型的两个实例是只有当所有属性都相等时才相等。