Thursday, September 10, 2009

Creating and saving XML using LINQ to XML in C#

XML generation is much easier now in C#. You can use System.Xml.Linq namespace to create XML content much faster and easy.
lets look at the following XML.
<Customer id="1" orderdate="4/1/1968">Paul Koch</Customer>
<Customer id="2" orderdate="7/5/1988">Bob Kelly</Customer>
<Customer id="3" orderdate="3/24/1990">Joe Healy</Customer>

Create XML using Linq to XML
Following describes how to create the above xml using xElements.
XElement xml = new XElement("Customers");
XElement Customer = new XElement("Customer");
Customer.Add(new XAttribute("id",1));
Customer.Add(new XAttribute("orderdate", "4/1/1968"));
Customer.Value = "Paul Koch";
Customer = new XElement("Customer");
Customer.Add(new XAttribute("id", 2));
Customer.Add(new XAttribute("orderdate", "7/5/1988"));
Customer.Value = "Bob Kelly";
Customer = new XElement("Customer");
Customer.Add(new XAttribute("id", 3));
Customer.Add(new XAttribute("orderdate", "3/24/1990"));
Customer.Value = "Joe Healy";
you can get the xml string by using xml.ToString()

Save  XML File using Linq to XML
in generally there should be a xml declaration when we are saving the file. as an example
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
So create a file like that add following code to bottom of the above code.

XDocument Xdoc = new XDocument();
XDeclaration Xdec = new XDeclaration("1.0", "utf-8", "yes");
Xdoc.Declaration = Xdec;

No comments: