tags:

views:

123

answers:

2

I have xml documents in a database field. The xml documents have no whitespace between the elements (no line feeds, no indenting).

I'd like to output them to the browser, formatted nicely. I would simply like linefeeds in there with some indenting. Is there an easy, preferably built-in way to do this?

I am using ASP.NET 3.5 and C#. This is what I have so far, which is outputting the document all in one line:

I'm about 99.9977% sure I am using the XmlWriter incorrectly. What I am accomplishing now can be done by writing directly to the response. But am I on the right track at least? :)

int id = Convert.ToInt32(Request.QueryString["id"]);
var auditLog = webController.DB.Manager.AuditLog.GetByKey(id);

var xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.OmitXmlDeclaration = true;

var xmlWriter = XmlWriter.Create(Response.OutputStream, xmlWriterSettings);
if (xmlWriter != null)
{
    Response.Write("<pre>");
    // ObjectChanges is a string property that contains an XML document
    xmlWriter.WriteRaw(Server.HtmlEncode(auditLog.ObjectChanges));
    xmlWriter.Flush();
    Response.Write("</pre>");
}

This is the working code, based on dtb's answer:

int id = Convert.ToInt32(Request.QueryString["id"]);
var auditLog = webController.DB.Manager.AuditLog.GetByKey(id);

var xml = XDocument.Parse(auditLog.ObjectChanges, LoadOptions.None);
Response.Write("<pre>" + Server.HtmlEncode(xml.ToString(SaveOptions.None)) + "</pre>");

Thank you for helping me!

+1  A: 

WriteRaw just writes the input unchanged to the underlying stream.

if you want to use built-in formatting, you need first to parse the XML and then convert it back to a string.

The simplest solution is possibly to use XLinq:

var xml = XDocument.Parse(auditLog.ObjectChanges);

Response.Write(Server.HtmlEncode(xml.ToString(SaveOptions.None)));

(This assumes auditLog.ObjectChanges is a string that represents well-formed XML.)

If you need more control over the formatting (indentation, line-breaks) save the XDocument to a MemoryStream-backed XmlWriter, decode the MemoryStream back to a string, and write the string HtmlEncoded.

dtb
Thanks for the additional options. But your code already does exactly what I want!
Chris
A: 

If auditLog.ObjectChanges is the XML content that needs to be formatted, then you've stored it in an unformatted way. To format it, treat it as XML and write it to an XMLWriter to format it. Then include the formatted XML into the response, with the HTML encoding.

Workshop Alex