You do not need linq to create this xml, you can use linq to generate collection and serialize the collection in an XML file.
Before serialization, you must add the Serializable attribute to 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;} }
See how to set up serialization (using attributes): http://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.80).aspx
Create a method for serializing:
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");
source share