-1
我有具有多個Invoice元素的XML輸入。我從這些元素創建發票對象。根據發票元素的位置,我們需要分配序列號並從不同的元素 - StatusMsg中找到相應的消息。更好的代碼用於創建對象並從XML更新其屬性
我在.NET 4.0中有下面的C#代碼。它工作正常,合理可讀。有沒有更好的代碼performance
而不犧牲readability
?
CODE
// 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>
");
參考:
- Generate c# object code and assign values to its properties from an xml document
- Use Annotations to Transform LINQ to XML Trees in an XSLT Style - Eric White
- Advantages of XSLT or Linq to XML
考慮'XmlSerializer.Deserialize()'。 MSDN鏈接 - http://msdn.microsoft.com/en-gb/library/tz8csy73.aspx – LukeHennerley 2013-03-20 12:36:14
除非他可以重新構造XML,反序列化不會做他那麼好。除發票序列外,他在StatusDetail和Invoice之間沒有定義的鏈接,這似乎相當浮躁。如果您有選擇,我建議重新構建。當然,你可以對它進行反序列化,然後使用發票列表索引對個別StatusDetail條目的序列進行...但是,對於很少的收益(如果有的話)來說,這似乎有很多工作。更多的內存密集以及.... – Nevyn 2013-03-20 13:09:45