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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: