public
Last active

Example of pretty-printing XML in C# using the XmlWriter class

  • Download Gist
PrettyXml.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;
 
static string PrettyXml(string xml)
{
var stringBuilder = new StringBuilder();
 
var element = XElement.Parse(xml);
 
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.NewLineOnAttributes = true;
 
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
element.Save(xmlWriter);
}
 
return stringBuilder.ToString();
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.