Creating XML Using LINQ to XML

Suppose I have a class that looks below, how to create xml as shown 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> 
+6
source share
3 answers

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"); 
+4
source

Although you can use XmlSerialization, there are quite a few cases where using LINQ to XML is just as simple and does not block the implementation of the class in a single serialization scheme. Here is some code to process 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); 
+19
source

You must respect the hierarchy.

By serializing this XML, we will have something like this:

 <Order> <OrderNo></OrderNo> <ItemId></ItemId> ... <Order> 

I think in this case you will have to write yourself, looking at the object and generating XML using XmlDocument, XElement or StringBuilder, for example.

+2
source

Source: https://habr.com/ru/post/948806/


All Articles