Linq to XML来填充父/子关系

时间:2018-05-25 22:26:18

标签: c# lambda linq-to-xml

我想填充两个具有父子关系的对象。这两个对象是PaymentInvoice。每个Payment可能适用于多个Invoice个对象,因为客户可以编写单个付款以涵盖多个发票。

class Payment
{
    public string PaymentId {get; set;}
    public decimal PaymentAmount {get; set;}
    public List<Invoice> InvoiceCollection {get; set;} // Collection of Invoices
}

class Invoice
{
    public string InvoiceId {get; set;}
    public decimal InvoiceAmount {get; set;}
    public DateTime InvoiceDate {get; set;}
}

我想使用LINQ to XML和Lambda语法将XML数据导入对象。我遇到的问题是获取信息的API调用返回多次付款。我可以针对每次付款进行单个API调用,但是当我可以通过单个API调用传递所有付款ID并获取所有数据时,这将是低效的。问题是我对如何解析它感到困惑,以至于我收回了一些Payment对象。是否可能或者我是否需要为每笔付款单独调用API?

<payment>
...
</payment>
<payment>
    <paymentId>7400</paymentId>
    <paymentAmount>540</paymentAmount>
    <paymentDate>05/22/2018</paymentDate>
    <invoice>
        <invoiceId>KADS333</invoiceId>
        <invoiceAmount>175</invoiceAmount>
        <invoiceDate>4/27/2018</invoiceDate>
    </invoice>
    <invoice>
        <invoiceId>53222</invoiceId>
        <invoiceAmount>300</invoiceAmount>
        <invoiceDate>4/04/2018</invoiceDate>
    </invoice>
    <invoice>
        <invoiceId>KAZO111</invoiceId>
        <invoiceAmount>65</invoiceAmount>
        <invoiceDate>3/12/2018</invoiceDate>
    </invoice>
</payment>
<payment>
...
</payment>

另外......我需要能够过滤掉K中没有字母InvoiceId的任何发票。例如53222。 (这些是机场代码,K始终存在于机场代码中。)

以下是我开始使用的Linq,但是我在填充PaymenModel以及InvoiceModel的{​​{1}}时遇到了问题。

PaymentModel

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这些要求,下面的代码应该产生想要的结果:

List<Payment> paymentDetails = xml.Descendants("payment")
        .Select(x => new Payment()
        {
            PaymentId = x.Element("paymentId").Value,
            PaymentAmount = (decimal)x.Element("paymentAmount"),
            InvoiceCollection = x.Elements("invoice")
                .Where(i => i.Element("invoiceId").Value.Contains("K"))
                .Select(i => new Invoice()
                {
                    InvoiceId = i.Element("invoiceId").Value.ToString(),
                    InvoiceAmount = (decimal)i.Element("invoiceAmount"),
                    InvoiceDate = (DateTime)i.Element("invoiceDate")
                }).ToList()
        }).ToList();

它会创建所有付款的列表,其中包含PaymentIdInvoiceCollection等属性,其中包含InvoiceId包含"K"的发票。