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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.