In C#, what is the best method to format a string as XML?

string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);

Output:

<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>

The Xml Declaration isn’t output by ToString(), but it is by Save() …

  XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
  Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));

Output:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <author>Lewis, C.S.</author>
  <title>The Four Loves</title>
</book>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)