我一直在使用Format XML String to Print Friendly XML String中的XML格式解决方案,但是我发现一些案例,我希望以可视方式格式化缺少元素的XML文档,或者以视觉方式格式化XML“样式”文档。
我正在尝试实现一种类似于https://www.webtoolkitonline.com/xml-formatter.html的解决方案,因为它似乎忽略了标签,并且仅根据层次结构进行格式化。我相信它们的实现基于RegEx。
我目前正在通过以下方式使用该实现:
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();
}
理想情况下,此输入:
<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>
将产生以下输出:
<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>