How do you create an indented XML string from an XDocument in c#?

JC. picture JC. · Mar 3, 2010 · Viewed 18.1k times · Source

I have an XDocument object and the ToString() method returns XML without any indentation. How do I create a string from this containing indented XML?

edit: I'm asking how to create an in memory string rather than writing out to a file.

edit: Looks like I accidentally asked a trick question here... ToString() does return indented XML.

Answer

John Saunders picture John Saunders · Mar 3, 2010
XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();