Tuesday, August 12, 2008

XDocument.ToStringWithXmlDeclaration() - Get the string representation of XDcoument with its Xml Declaration

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

15 {

16 static void Main(string[] args)

17 {

18

19 XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("root"));

20 Console.WriteLine(doc.ToStringWithXmlDeclaration());

21 }

22 }

23

24

25 public static class XDocumentExtensions

26 {

27 public static string ToStringWithXmlDeclaration(this XDocument doc)

28 {

29 StringBuilder builder = new StringBuilder();

30 StringWriter writer = new StringWriter(builder);

31 doc.Save(writer);

32 writer.Flush();

33 return builder.ToString();

34 }

35 }

Apart from its purpose, this is also an example use of the Extension Method feature of C# 3.0.