I am using the below method to convert a list to XML. How can I alter this in order to convert a nested list in to XML.
private string ConvertProductListToXML(List<ProductDM> productDMList)
{
var xEle = new XElement("Products",
from emp in productDMList
select new XElement("Product",
new XElement("ProductID", emp.ProductID),
new XElement("Cost", emp.Cost),
new XElement("UPC", emp.UPC),
new XElement("TaxStatus", emp.TaxStatus)
));
return ConvertToInnerXML(xEle);
}
public static string ConvertToInnerXML(XElement el)
{
var reader = el.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
Model
public class ProductDM
{
public int? ProductID { get; set; }
public string UPC { get; set; }
public string TaxStatus { get; set; }
public Decimal Cost { get; set; }
}
How can I modify the above code if the data model looks like below with an extended list.
public class ProductDM
{
public int? ProductID { get; set; }
public string UPC { get; set; }
public string TaxStatus { get; set; }
public Decimal Cost { get; set; }
public List<InventoryDM> CabinetList { get; set; }
}
public class InventoryDM
{
public int InventoryID { get; set; }
}
Expected output :
<Product><ProductID>40</ProductID><Cost>2</Cost><UPC>3121</UPC>
<TaxStatus>NO</TaxStatus><CabinetList>
<InventoryID>1</InventoryID></CabinetList><CabinetList>
<InventoryID>2</InventoryID></CabinetList></Product>
I wouldn't use xElement. The easiest solution is to use xml serialization. Your class should be updated like this
And to serialze the class to xml