Pretty print XML data in JSP

ぐ巨炮叔叔 提交于 2020-01-17 03:55:06

问题


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.


回答1:


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>



回答2:


If you want a simple solution, don't bother with xsl while setting response for JSP to look at, just do stuff.replaceAll("<", "& lt;").replaceAll(">","& gt; "); You don't need anything else; no XSL transformation needed here. Use technologies when they are essential, unless I am missing something here.




回答3:


You can pretty print JSLT with Pretty Diff at http://prettydiff.com/?m=beautify It will do exactly what you need. Consider the following example:

<a>
    <c:out value="<strong>some content</strong>"/>
</a>

Pretty Diff is capable of recognizing multidimensional tags so long as the nested tag is in quotes.



来源:https://stackoverflow.com/questions/5903716/pretty-print-xml-data-in-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!