countryroadscat
countryroadscat

Reputation: 1750

How to treat XML tags like a plain text in JSP page

I want to print a text file uploaded on my server on my JSP page. That text file contains XML tags.

I already find how to read a text file from URL to string and how to print it. Im doing it like this:

<%  
    URL website = new URL("this is my url");
    URLConnection connection = website.openConnection();
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                                connection.getInputStream()));

    StringBuilder response1 = new StringBuilder();
    //response1.append("<![CDATA[");
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        response1.append(inputLine+"\n");
    }
    //response1.append("]]>");
    out.println(response1.toString());  
    in.close();
%>

However when i open my JSP page im getting only text. All my XML tags disapears.

What to do to print them aswell?

As u can see, i have tried to do CDATA but it isnt working.

Edit:

As @markbernard suggested, I need to use escapeXml(String) method from StringEscapeUtils. If u got maven, just add dependecy, if not download a lib into your Web-INF/lib directory.

Usage for my case:

String result = response1.toString();
out.println(StringEscapeUtils.escapeXml(result));

Upvotes: 1

Views: 744

Answers (1)

markbernard
markbernard

Reputation: 1420

You need to convert the tags to entities so it will display instead of parse. Apache Commons has a StringEscapeUtils class that will do the encoding for you. The library can be found at http://commons.apache.org/proper/commons-lang/ and the class you want to use is https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

Upvotes: 2

Related Questions