using System.Collections.Generic;
public static class XmlExtensions
public static string FormatXml(this string xml,
bool indent = true, bool newLineOnAttributes = false, string indentChars = " ",
ConformanceLevel conformanceLevel = ConformanceLevel.Document, bool ignoreWhitespace = true) =>
xml.FormatXml( new XmlWriterSettings { Indent = indent, NewLineOnAttributes = newLineOnAttributes, IndentChars = indentChars, ConformanceLevel = conformanceLevel },
new XmlReaderSettings { ConformanceLevel = conformanceLevel, IgnoreWhitespace = ignoreWhitespace });
public static string FormatXml(this string xml, XmlWriterSettings writerSettings, XmlReaderSettings? readerSettings = default)
using (var textReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(textReader, readerSettings ))
using (var textWriter = new StringWriter())
using (var xmlWriter = XmlWriter.Create(textWriter, writerSettings))
xmlWriter.WriteNode(xmlReader, true);
return textWriter.ToString();
public static void Test()
foreach (var inXml in GetXml())
var newXml = inXml.FormatXml(indentChars : "", newLineOnAttributes : false);
Console.WriteLine(newXml);
Assert.IsTrue(XNode.DeepEquals(XDocument.Parse(inXml), XDocument.Parse(newXml)));
static IEnumerable<string> GetXml() => new []
@"<?xml version='1.0'?><response><error code='1'> Success</error></response>",
<error code='1'> Success</error>
<?xml version="1.0" encoding="iso-8859-1"?>
<b>Now</b> is the winter of our discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the deep bosom of the ocean buried.
public static void Main()
Console.WriteLine("Environment version: {0} ({1}, {2}, NewLine: {3}).",
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion,
System.Text.Json.JsonSerializer.Serialize(Environment.NewLine));
Console.WriteLine("Failed with unhandled exception: ");