The System.Xml.Linq.XDocument.ToString() produces a serialized string version of the XDocument object. But unfortunately, while doing so, it leaves the xml declaration in the serialized version which may be required in your application.
Again, there is another method called Save that produces the serialized version including xml declaration. So, I think we can write a simple extension method for producing the xml declaration as shown in the following -
14 class Program
16 static void Main(string args)
19 XDocument doc = new XDocument(new XDeclaration(“1.0”, “utf-8”, null), new XElement(“root”));
25 public static class XDocumentExtensions
27 public static string ToStringWithXmlDeclaration(this XDocument doc)
29 StringBuilder builder = new StringBuilder();
30 StringWriter writer = new StringWriter(builder);
33 return builder.ToString();
Apart from its purpose, this is also an example use of the Extension Method feature of C# 3.0.