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>
LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.
The LINQ to XML will bring the XML document into memory and allows us to write LINQ Queries on in-memory XML document to get the XML document elements and attributes. To use LINQ to XML functionality in our applications, we need to add "System. Xml. Linq" namespace reference.
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With