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
No comments:
Post a Comment