将 xml 数据规范化为对象 linq to xml

本文关键字:xml linq to 对象 规范化 数据 | 更新日期: 2023-09-27 18:30:54

你好,我有这个xml,我想得到一个计划列表和计划条款列表。

   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);

这给了我三个顶级计划记录,但我只想要一个计划记录(因为名称总是"高级")有三个术语。您能否建议一些调整来解决此问题。

将 xml 数据规范化为对象 linq to xml

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

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>()
};

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