ryanprayogo ryanprayogo - 7 months ago 56
HTML Question

Pretty print XML data in JSP

How do I pretty print (ie. with indentation) XML data in the JSP? I have the following code:

<c:forEach items="${stuffs}" var="stuff">
<pre>
<c:out value="${stuff}" escapeXml="true"/><br/>
</pre>
</c:forEach>


But the problem is when
${stuff}
is an unformatted XML, it will show in the jsp as one long XML data. I need it pretty-printed inside the
<p>
tag.

Answer

XSLT has a simple means of doing this via the xsl:output element. If you can apply an XSLT, I suggest using a stylesheet like this (based on the identity transformation):

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:strip-space elements="*" />
    <xsl:output method="xml" indent="yes" />
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>