Mega Code Archive

 
Categories / C# Book / 05 LINQ XML
 

0541 Serialize an XDocument

Serialize an XDocument to a string with the XML declaration. using System; using System.Text; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static void Main() { var doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement("test", "data") ); var output = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true }; using (XmlWriter xw = XmlWriter.Create(output, settings)) doc.Save(xw); Console.WriteLine(output.ToString()); } } The output: data