How to get Xml as string from XDocument?

Ashish Gupta picture Ashish Gupta · Dec 26, 2010 · Viewed 73.2k times · Source

I am new to LINQ to XML. After you have built XDocument, how do you get the OuterXml of it like you did with XmlDocument?

Answer

user432219 picture user432219 · Dec 26, 2010

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.