![]() |
Languages »
C / C++ Language »
General
Intermediate
Formatting XML - A Code snippetBy Ian RandellHow to quickly format XML for a nicer display. |
C#, XML, Windows, .NET, Visual Studio, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||
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.
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.
using System.Text;
using System.Xml;
. . .
/// <summary>
/// Returns formatted xml string (indent and newlines) from unformatted XML
/// string for display in eg textboxes.
/// </summary>
/// <param name="sUnformattedXml">Unformatted xml string.</param>
/// <returns>Formatted xml string and any exceptions that occur.</returns>
private string FormatXml(string sUnformattedXml)
{
//load unformatted xml into a dom
XmlDocument xd = new XmlDocument();
xd.LoadXml(sUnformattedXml);
//will hold formatted xml
StringBuilder sb = new StringBuilder();
//pumps the formatted xml into the StringBuilder above
StringWriter sw = new StringWriter(sb);
//does the formatting
XmlTextWriter xtw = null;
try
{
//point the xtw at the StringWriter
xtw = new XmlTextWriter(sw);
//we want the output formatted
xtw.Formatting = Formatting.Indented;
//get the dom to dump its contents into the xtw
xd.WriteTo(xtw);
}
finally
{
//clean up even if error
if (xtw != null)
xtw.Close();
}
//return the formatted xml
return sb.ToString();
}
Happy coding!
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 14 Jan 2007 Editor: Chris Maunder |
Copyright 2007 by Ian Randell Everything else Copyright © CodeProject, 1999-2009 Web13 | Advertise on the Code Project |