Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate xml using LINQ to XML

Tags:

c#

xml

linq

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>
like image 967
ryman Avatar asked Jul 05 '13 16:07

ryman


People also ask

Can we use LINQ for XML?

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.

Which of the following option is created to retrieve data into XML using LINQ?

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.

What is the difference between XDocument and XmlDocument?

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 .


1 Answers

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);
like image 148
Jim Wooley Avatar answered Nov 21 '22 10:11

Jim Wooley