I've been using the XML Formatting solution from Format XML String to Print Friendly XML String, however I'm finding cases that I want to visually format XML documents that are missing elements, or I want to visually format XML 'style' documents.
I'm trying to achieve a solution similar to https://www.webtoolkitonline.com/xml-formatter.html as it seemingly ignores tags, and does formatting only based on hierarchy. I believe their implementation is based on RegEx.
I'm currently using the implementation in the following way:
private void FormatXML_Click(object sender, RoutedEventArgs e)
{
var holdXML = TextEditor.Text;
TextEditor.Clear();
try {
TextEditor.Text = PrintXML(holdXML);}
catch {
TextEditor.Text = holdXML;}
}
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();
}
Ideally this input:
<shipto><name>Ola Nordmann</name><address>Langgt 23</address><city>4000 Stavanger</city><country>Norway</country></shipto><item><title>Empire Burlesque</title><note>Special Edition</note><quantity>1</quantity><price>10.90</price></item><item><title>Hide your heart</title><quantity>1</quantity><price>9.90</price></item>
Would produce this output:
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>