使用LINQ读取XML不同的节点

时间:2014-02-06 19:06:43

标签: c# xml linq xml-parsing linq-to-xml

我在字符串中有以下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:20,金额:$ 50.00,精选:真
  • 附加费ID:15,金额:25.00美元,精选:假

假设

我们还假设具有相同ID的任何附加费将始终具有相同的SurchargeAmountSurchargeSelected个值。例如, 从不 是ID为20的两个附加费FALSETRUE 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();

提前感谢任何可以帮助我的人!! :)

2 个答案:

答案 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

它使用的事实是,匿名类型默认定义了EqualsGetHashCode

  

因为匿名类型上的EqualsGetHashCode方法是根据属性的EqualsGetHashcode方法定义的,所以同一个匿名类型的两个实例是只有当所有属性都相等时才相等。

     来自Anonymous Types (C# Programming Guide)