I created the routine below based on a StackOverflow that gave me the idea. In BizTalk Orchestrations, we often email out error to a distribution list, and it’s a lot easier on the eye when the request and response XML messages are nicely formatted. “Pretty Print” is a term used by several utilities like XML Spy and the XML Tools PlugIn for NotePad++.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; namespace MySite.Common.BizTalkUtil { public static class XmlFormatter { // Neal Walters - added 09/11/2015 from // http://stackoverflow.com/questions/203528/what-is-the-simplest-way-to-get-indented-xml-with-line-breaks-from-xmldocument public static string PrettyPrint(this XmlDocument doc) { var stringWriter = new StringWriter(new StringBuilder()); var xmlTextWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented }; doc.Save(xmlTextWriter); return stringWriter.ToString(); } } }
Example Use:
//tempStrBuilder is an object of type StringBuilder tempStrBuilder.Append("There was a SOAP 1.1 Fault. Check service for errors." + System.Environment.NewLine); tempStrBuilder.Append("===========================" + System.Environment.NewLine); tempStrBuilder.Append("Inbound Request:" + System.Environment.NewLine); tempStrBuilder.AppendLine(MySite.Common.BizTalkUtil.XmlFormatter.PrettyPrint(xmlDocReq)); tempStrBuilder.Append("===========================" + System.Environment.NewLine); tempStrBuilder.Append("SOAP Fault:" + System.Environment.NewLine); tempStrBuilder.Append(MySite.Common.BizTalkUtil.XmlFormatter.PrettyPrint(vSOAPErrorXML)); // Then the error can be include in the body of an email
Pretty Print XML in NotePad++
If you just need to format XML on your PC, consider adding the XML PlugIn for NotePad++ (a great free editor).
CNLT-ALT-SHIFT-B is the short cut, if you have enough fingers!
To install the Plugin, open the Plugin Manager as shown below. Scroll down to the XML Plugin, and simply install it, then it restarts NotePad++ and it should be there. Only takes two minutes or less.
Pretty Print XML in XSLT or BizTalk Mapper
From the map grid, right-click properties. In the properties window, not the “Indent” property, which says “Specified additional white space to add whne outputing the result tree; the value must be “yes” or “no”.
Presumably, that would set the XSLT code as follows, but I haven’t proven that yet.
<pre>
<xsl:output method="xml" indent="yes"/>
</pre>
Reference: XSLT Syntax for Indenting, i.e. Pretty Print