Reputation: 105
Suppose that I have a class that looks like below, how do I create xml like below using LINQ to XML?
public class Order
{
public string OrderNo {get; set;}
public string ItemId {get; set;}
public string ItemDesc {get; set;}
public int Qty {get; set;}
}
<orders>
<orderid>
<orderno>1</orderno>
<itemid>W001</itemid>
<itemdesc>C# T-Shirst</itemdesc>
<quantity>2</quantity>
</orderid>
<orderid>
<orderno>2</orderno>
<itemid>W002</itemid>
<itemdesc>XML T-Shirt</itemdesc>
<quantity>1</quantity>
</orderid>
</orders>
Upvotes: 8
Views: 11672
Reputation: 10418
While you can use XmlSerialization, there are quite a number of cases where using LINQ to XML is just as easy and doesn't lock your class implementation into a single serialization scheme. Here's a bit of code to handle your request.
var xOrders = new XElement("orders",
from o in Orders
select new XElement("orderid",
new XElement("orderno", order.OrderNo),
new XElement("itemid", order.ItemId),
new XElement("itemdesc", order.ItemDesc),
new XElement("quantity", order.Qty)));
xOrders.Save(targetPath);
Upvotes: 24
Reputation: 38638
You do not need linq to generate this xml, you could use linq to generate a collection
and serialize the collection in a xml file.
Before serializing, you should add the Serializable
attribute in your class:
[Serialize]
public class Order
{
public string OrderNo {get; set;}
public string ItemId {get; set;}
public string ItemDesc {get; set;}
public int Qty {get; set;}
}
Take a look here how to customize your serialization (using attributes): http://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.80).aspx
Create a method like this to serialize:
public statc void SerializeOrders(Order[] orders, string path)
{
XmlSerializer parse = new XmlSerializer(typeof(Order[]));
using (var writer = new StreamWriter(path))
{
parse.Serialize(writer, orders);
writer.Close();
}
}
And deserialize:
public statc Order[] Deserialize(string path)
{
XmlSerializer ser = new XmlSerializer(typeof(Order[]));
Order[] result;
using (XmlReader reader = XmlReader.Create(path))
{
result = (Order[]) ser.Deserialize(reader);
}
return result;
}
And use it:
// get the collection
var orders = (from o in Queryable<Order>
where o.Something
select o).ToArray();
// serializing in xml
SerializeOrders(orders, "C:\\result.xml");
// deserializing the xml
var serializedOrders = Deserialize("C:\\result.xml");
Upvotes: 5
Reputation: 2987
You have to respect the hierarchy.
Serializing this XML, we'll have something like this:
<Order>
<OrderNo></OrderNo>
<ItemId></ItemId>
...
<Order>
I think in this case, you will have to write on your own reading the object and generating the XML using XmlDocument, XElement or a StringBuilder for example.
Upvotes: 2