how to display xml formatted jsp
I have XML as a string in JSP. But this XML is in a single line. I want to display this XML string formatted in JSP.
For example:
<?xml version="1.0"?><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price>...(is going on)
I want to display this as follows in JSP:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
开发者_运维技巧 <genre>Computer</genre>
<price>44.95</price>...(going on)
How can I do this?
I have the exact same problem. I solved it by formatting the XML string in my Java Code before sending it to the JSP (you can do it in JSP also if you want):
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Source source = new DOMSource(document);
StringWriter writer = new StringWriter();
Result output = new StreamResult(writer);
transformer.transform(source, output);
return writer.toString();
Then use c:out to display it
<pre>
<c:out value="${xmlString}" />
</pre>
You need to convert the <, > and other characters which have special meaning in HTML to their HTML entities. To parse use this method. It will parse for you.
do xsl transformation and specify option
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select="."/>
</xsl:template>
see this example and after this use your xml
Try to change "text/xml" instead of "text/html" in your jsp:
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
then put xml content without
<?xml version="1.0"?>
So you need something like this:
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price>...(is going on)
精彩评论