2

您好,我有这个 xml,我想获取计划列表和 PlanTerms 列表。

   Plan
    {
    name = "Premium"
    List<Terms>{
      24 months/24000 miles
     36 months/36000 miles
    }

    }

XML:

<plan>
    <planid>1</planid>
    <plantitle>Premium</plantitle>
    <plandesc>12 months / 12,000 miles</plandesc>
    <planwarranty>NA</planwarranty>
    <plancoveredterm>12</plancoveredterm>

</plan>
<plan>
    <planid>2</planid>
    <plantitle>Premium</plantitle>
    <plandesc>24 months / 24,000 miles</plandesc>
    <planwarranty>NA</planwarranty>
    <plancoveredterm>24</plancoveredterm>

</plan>
<plan>
    <planid>3</planid>
    <plantitle>Premium</plantitle>
    <plandesc>36 months / 36,000 miles</plandesc>
    <planwarranty>NA</planwarranty>
    <plancoveredterm>36</plancoveredterm>

</plan>

我正在使用以下代码块

XDocument xdoc = XDocument.Parse(providerResponse);
XElement root = xdoc.Root;

var quotePlan = (from planInfo in root.Descendants("plan")
                 select new QuotePlanMbp
                 {
                     Name = planInfo.Element("plantitle").Value.ToString(),
                     QuoteTerms = (from planTerm in root.Descendants("plan")
                                   select new QuoteTermMbp
                                   {
                                       TermMonths = planTerm.Element("plancoveredterm").Value != null ? Convert.ToInt32(planTerm.Element("plancoveredterm").Value) : 0,
                                       TermMiles = planTerm.Element("plancoveredmiles").Value != null ? Convert.ToInt32(planTerm.Element("plancoveredmiles").Value) : 0,
                                       TermCost = planTerm.Element("plancost").Value != null ? Convert.ToDecimal(planTerm.Element("plancost").Value) : 0
                                   }).ToList<QuoteTerm>()
                  }).GroupBy(plan => plan.Name);

这给了我三个顶级计划记录,但我只想要一个包含三个术语的计划记录(因为名称始终是“高级”)。你能否建议一些调整来解决这个问题。

4

1 回答 1

2

在选择条款之前,您应该按名称对计划进行分组。然后为每个计划组选择条款列表:

from planInfo in root.Descendants("plan")
group planInfo by (string)planInfo.Element("plantitle") into g
select new QuotePlanMbp {
   Name = g.Key,
   QuoteTerms = 
      (from planTerm in g
       let months = (int?)planTerm.Element("plancoveredterm")
       select new QuoteTermMbp {
           TermMonths = months.GetValueOrDefault(),
           TermMiles = (int)((int?)planTerm.Element("plancoveredmiles") ?? 0),
           TermCost = ((int?)planTerm.Element("plancost")).GetValueOrDefault()
       }).ToList<QuoteTermMbp>()
};

我还在这里展示了三种不同的解析术语整数属性的技术——选择你更喜欢的一种。

于 2013-09-10T19:52:20.393 回答