How to get Xml as string from XDocument?

You only need to use the overridden ToString() method of the object:

XDocument xmlDoc ...
string xml = xmlDoc.ToString();

This works with all XObjects, like XElement, etc.


I don't know when this changed, but today (July 2017) when trying the answers out, I got

"System.Xml.XmlDocument"

Instead of ToString(), you can use the originally intended way accessing the XmlDocument content: writing the xml doc to a stream.

XmlDocument xml = ...;
string result;

using (StringWriter writer = new StringWriter())
{
  xml.Save(writer);
  result = writer.ToString();
}

Doing XDocument.ToString() may not get you the full XML.

In order to get the XML declaration at the start of the XML document as a string, use the XDocument.Save() method:

    var ms = new MemoryStream();
    using (var xw = XmlWriter.Create(new StreamWriter(ms, Encoding.GetEncoding("ISO-8859-1"))))
        new XDocument(new XElement("Root", new XElement("Leaf", "data"))).Save(xw);
    var myXml = Encoding.GetEncoding("ISO-8859-1").GetString(ms.ToArray());