tags:

views:

132

answers:

2

I want to display an exception trace in the HTML page.

One way to do this is to escape HTML special characters in the exception trace and dump it inside the <pre> tag.

Although it works, it's terribly inefficient. I thought that one approach would be to wrap the trace with CDATA. I've tried it, but nothing get's displayed.

My question, can this be done?

Here is my feeble attempt.

  <pre><![CDATA[blah, blah, blah with <>
  and blah blah blah with &
    and more blah, blah]]></pre>
+1  A: 

Yes, but only in XHTML (in theory, I think it should work in HTML, but web browsers deal in tag soup not HTML 4.x) and not if you serve the document as text/html (which you have to if you want it to work with Internet Explorer).

As far as efficiency goes, replacing <, & and > with their respective entities is a trivial operation in any programming language (or text editor with a Find & Replace facility), which doesn't add a significant number of bytes except in conditions of extremely limited bandwidth.

David Dorward
+3  A: 

It would only work if you're serving the page as XML (application/xhtml+xml); there are no CDATA sections in plain HTML. Most browsers in HTML mode would just ignore the example CDATA section.

And throwing <![CDATA[...]]> around a string is not sufficient to wrap it, anyway. If your trace information had the sequence ]]> in it, that'd end the CDATA section and you'd be back at the same problem. So you have to do at least one escape to cope with that case, and if you're going to be doing an escaping process anyway you might as well do a proper HTML-escape.

This is why CDATA sections are largely pointless. A lot of people seem to think it somehow absolves them of thinking about escaping issues, but it really doesn't.

Anyway, HTML-escaping isn't inefficient. It's a couple of string replaces. Any web app(*) will be doing a hundred HTML-escapes every page. Adding one more — especially for a debugging case where efficiency doesn't matter at all! — is no great burden.

(*: well, except for poorly-written apps from PHP tutorials, whose authors have never even heard of htmlspecialchars, obviously.)

bobince