28 February 2016 XML, .NET Robert Muehsig

Pretty Print

The term “pretty print” describes that a document is more or less human readable formatted. So instead of this:


You might want to get this:


Many editors support this feature - but we want to do it in code.

Pretty Print XML with .NET

The code is really simple, because XDocument does the heavy lifting for us.

var xDocument = XDocument.Parse(input);
string formattedXml = xDocument.ToString();

// Force XML Declaration if present
if (xDocument.Declaration != null)
  formattedXml = xDocument.Declaration + Environment.NewLine + formattedXml;
return formattedXml;

This should work in most cases - there might be some issues with comments or maybe special XML chars. If you have a better idea, please let me know.

Hope this helps!

Written by Robert Muehsig

Software Developer - from Dresden, Germany, now living & working in Switzerland. Microsoft MVP & Web Geek.
Other Projects: ExpensiveMeeting | EinKofferVollerReisen.de

blog comments powered by Disqus