Format XML string to print friendly XML string

Graviton picture Graviton · Jul 14, 2009 · Viewed 207.5k times · Source

I have an XML string as such:

<?xml version='1.0'?><response><error code='1'> Success</error></response>

There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:

<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response> 

Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand?

Answer

Charles Prakash Dasari picture Charles Prakash Dasari · Jul 14, 2009

You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.

string FormatXml(string xml)
{
     try
     {
         XDocument doc = XDocument.Parse(xml);
         return doc.ToString();
     }
     catch (Exception)
     {
         // Handle and throw if fatal exception here; don't just ignore them
         return xml;
     }
 }

[using statements are ommitted for brevity]