Using Linq to XML to create existing object based on class/model - working, but is there a better way?



A webservice I use (I have no control over it) returns an XML string, which I convert to an XDcoument and then create a list of objects of a particular type:



private static List<ProductDetail> productList(XmlDocument _xDoc) {
XDocument xdoc = XDocument.Load(new XmlNodeReader(_xDoc));
var pList = from p in xdoc.Root.Elements("DataRow")
select new ProductDetail
{
Product = (string)p.Element("Product"),
ProductDesc = (string)p.Element("ProductDesc"),
ExtraKey = (string)p.Element("ExtraKey"),
SalesGroup = (string)p.Element("SalesGroup"),
Donation = (string)p.Element("Donation"),
Subscription = (string)p.Element("Subscription"),
StockItem = (string)p.Element("StockItem"),
MinimumQuantity = (string)p.Element("MinimumQuantity"),
MaximumQuantity = (string)p.Element("MaximumQuantity"),
ProductVATCategory = (string)p.Element("ProductVATCategory"),
DespatchMethod = (string)p.Element("DespatchMethod"),
SalesDescription = (string)p.Element("SalesDescription"),
HistoryOnly = (string)p.Element("HistoryOnly"),
Warehouse = (string)p.Element("Warehouse"),
LastStockCount = (string)p.Element("LastStockCount"),
UsesProductNumbers = (string)p.Element("UsesProductNumbers"),
SalesQuantity = (string)p.Element("SalesQuantity"),
AmendedBy = (string)p.Element("AmendedBy")
};
return pList.ToList();
}


This works fine and is very fast. However it means I have to maintain this code separately from the model if it changes and I was just wondering if there was a shortcut to avoid me having to specify each individual field as I'm doing? I already have a class for ProductDetail so is there some way of using that at the object level? I've a feeling that the answer may be "yes, but using reflection" which will probably have a negative impact on the process speed so is not something I'd be keen on.


No comments:

Post a Comment