Serialize XDocument in LINQ To XML

In this post, we will first create an XDocument object that contains XElement objects. You can then serialize the XDocument to a File, XMLWriter or TextWrite

Let us see how to Serialize an XDocument in LINQ to XML to an XMLWriter and then to the disk.

Make sure you add references to the following namespaces:

using System.Xml.Linq;
using System.IO;
using System.Xml;

static void Main(string[] args)
{
XNamespace empNM = "urn:lst-emp:emp";

XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement("Employees",
new XElement("Employee",
new XComment("DevCurry.com Employees"),
new XElement("EmpId", "1"),
new XElement("Name", "Kathy"),
new XElement("Sex", "Female")
)));

using (StringWriter strW = new StringWriter())
{
using (XmlWriter xmlW = XmlWriter.Create(strW))
{
xDoc.Save(xmlW);
// Save to Disk
xDoc.Save("C:\\XDocSerialized.xml");
Console.WriteLine("Saved");
}
}

Console.ReadLine();
}

Open the XDocSerialized.xml file in notepad and you should see the following output

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: