tags:

views:

165

answers:

2

How can I include a XML file as content in a textarea element in a XHTML document? It will cause validation errors if the special characters are not escaped.

Is there an easy way in JSP to escape special characters before they are inserted using the include directive, like using the JSTL?

Example code:

    <div>
        <textarea name="content" rows="20" cols="80"><%@ include file="example.xml" %></textarea>
    </div>

This will look fine in a browser, but XHTML validation will fail because the embedded file starts another XML declaration.

A: 

You probably want to embed your <%@ include %> within a <![CDATA[...]]> so it is considered as plain text rather than XML parts. You can read this to get a bit more insight on what CDATA is for.

Romain
That only works if the document is served with an XML content type (such as application/xhtml+xml) most uses of XHTML serve it as text/html so CDATA markers are ignored.
David Dorward
+4  A: 

The "official" JSTL way of doing this is as follows:

<c:import url="example.xml" var="xmlContent"/>

<textarea><c:out value="${xmlContent}" escapeXml="true"/></textarea>

The escapeXml attribute defaults to true anyway, but it's probably wise to specify it here, for reasons of documentation.

skaffman
You probably means it defaults to `true`...?
Romain
s/defaults to false/defaults to true. Nevertheless +1.
BalusC
Oops, sorry yes, I thought "true" and typed "false".
skaffman
It works like a charm! Thank you for the quick help
mjustin