omer
omer

Reputation: 35

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?

Upvotes: 1

Views: 12962

Answers (4)

Wei Zhu
Wei Zhu

Reputation: 647

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>

Upvotes: 1

Mihai
Mihai

Reputation: 333

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)

Upvotes: 0

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12064

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

Upvotes: 0

Harry Joy
Harry Joy

Reputation: 59694

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.

Upvotes: 0

Related Questions