我有多个 Invoice 元素的 XML 输入。我从这些元素创建发票对象。根据 invoice 元素的位置,我们需要分配序列号并从不同的元素 - StatusMsg 中找到相应的消息。
我在 .Net 4.0 中有以下 C# 代码。它工作正常且可读性强。performance
在不牺牲的情况下有没有更好的代码readability
?
代码
// Create a collection of invoice elements
var invoiceEntities = xDoc.Descendants("Invoice")
.Select(x => new Invoice
{
Vendor = x.Element("Vendor") == null ? String.Empty : x.Element("Vendor").Value.Trim(),
Amount = x.Element("Amount") == null ? String.Empty : x.Element("Amount").Value.Trim()
});
List<Invoice> invoices = invoiceEntities.ToList();
//Iterate all entities for finding corresponding message element and update the entity's Message
int count = 0;
foreach (Invoice entity in invoices)
{
count++;
//Dynamic XPath statement
string messagePath = @"Status/StatusMsg/StatusDetail/Sequence[text()=" + count.ToString() + "]/../Message";
var statusDetails = xDoc.XPathSelectElements(messagePath).FirstOrDefault();
if (statusDetails != null)
{
entity.Message = statusDetails.Value;
entity.Sequence = count;
}
}
实体
public class Invoice
{
public string Vendor { get; set; }
public string Amount { get; set; }
public string Message { get; set; }
public int Sequence { get; set; }
}
XML
XDocument xDoc = XDocument.Parse(@"
<Status>
<StatusMsg>
<StatusType>INVOICE</StatusType>
<StatusCode>READYPAY</StatusCode>
<StatusTimestamp>2013-03-19T21:20:54Z</StatusTimestamp>
<StatusDetail>
<Sequence test=""K""> 2 </Sequence>
<Message>STL MESSAGE </Message>
</StatusDetail>
<StatusDetail>
<Sequence test=""1""> 1 </Sequence>
<Message>AKP MESSAGE</Message>
</StatusDetail>
<StatusDetail>
<Sequence> 1 </Sequence>
<Message>CC</Message>
</StatusDetail>
</StatusMsg>
<Invoices>
<Invoice>
<Vendor>
AKP LLC
</Vendor>
<Amount>
100
</Amount>
</Invoice>
<Invoice>
<Vendor>
STL Inc
</Vendor>
<Amount>
20950
</Amount>
</Invoice>
</Invoices>
</Status>
");
参考资料: