Anders Borum wrote:
[color=blue]
> Just create an XmlTextWriter with indenting as formatting. Then run your
> unformatted string through the writer and voila, a perfectly formatting Xml
> document as string. This is also called pretty-printing!
>
> /// <summary>
> /// Formats the string Xml for better readability.
> /// </summary>
> /// <param name="XmlString">The Xml to format.</param>
> /// <returns>A string formatted as Xml with indenting.</returns>
> public static string FormatXml(string xmlString)
> {
> XmlDocument XmlDoc = new XmlDocument();
> XmlDoc.LoadXml(xmlString);
>
> StringWriter sW = new StringWriter();
>
> XmlTextWriter XmlW = new XmlTextWriter(sW);
> XmlW.Formatting = Formatting.Indented;
>
> XmlDoc.DocumentElement.WriteContentTo(XmlW);
>
> XmlW.Close();
> return sW.ToString();
> }[/color]
Sorry for nitpicking again, Anders ;)
There is much more effective way of indenting XML, which doesn't require
to load the whole document into memory - XmlReader/XmlWriter pipeline.
It should be much faster and memory friendly:
XmlTextReader r = new XmlTextReader(new StringReader(xmlString));
r.MoveToContent();
StringWriter sw = new StringWriter();
XmlTextWriter w = new XmlTextWriter(sw);
w.Formatting = Formatting.Indented;
w.WriteNode(r,false);
w.Close();
return sw.ToString();
--
Oleg Tkachenko
XML Insider
http://www.tkachenko.com/blog