Introduction
I know this is basic stuff for many here, but as I couldn't find any similar article on this site I thought Id share this useful code snippet for those not so au-fait with the Xml classes.
Basically, I wanted a quick and easy way to get from a non-formatted string of XML, to something that could be nicely displayed in a textbox (ie with indenting and line breaks) without too much mucking about.
Using the code
Simple. Just call the method and display the result, eg. in a Windows forms textbox. Displaying in Webform elements may need the newline characters changed which can be done easily using String.Replace
.
The code:
using System.Text;
using System.Xml;
. . .
private string FormatXml(string sUnformattedXml)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(sUnformattedXml);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = null;
try
{
xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xd.WriteTo(xtw);
}
finally
{
if (xtw != null)
xtw.Close();
}
return sb.ToString();
}
Happy coding!