CSharp · Console
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using NUnit.Framework; //NUnit.Framework.AssertionException
#nullable enable
//https://stackoverflow.com/questions/1123718/format-xml-string-to-print-friendly-xml-string
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) =>
// By default we ignore the incoming whitespace, since the purpose of this method is to reformat the incoming xml.
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 class TestClass
{
public static void Test()
{
foreach (var inXml in GetXml())
{
var newXml = inXml.FormatXml(indentChars : "", newLineOnAttributes : false); // Or true, if you prefer
Console.WriteLine(newXml);
Assert.IsTrue(XNode.DeepEquals(XDocument.Parse(inXml), XDocument.Parse(newXml)));
Console.WriteLine();
}
}
static IEnumerable<string> GetXml() => new []
{
@"<?xml version='1.0'?><response><error code='1'> Success</error></response>",
"""
<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>
""",
"""
<?xml version="1.0" encoding="iso-8859-1"?>
<reportResponse>
<report>
<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.
</report>
</reportResponse>
""",
};
}
public class Program
{
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();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}