0

This prints my xml document on the console with pretty print.

//writing output to a file    
Document writeDocument = new Document(document);
//Formatting the file
Serializer serializer = new Serializer(System.out, "UTF-8");
serializer.setIndent(4);
serializer.write(writeDocument);

I need to return the same xml document, so that I can display it in browser.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Lalu
  • 1
  • 3

1 Answers1

0

I had the exact same requirement in one of my apps. You can do this by taking the serialized XOM document, wrapping it in code tags, and escaping the angle brackets. The example code below shows one way to do this:

     public String getHTMLDoc(Document document) {
        try {
            // create a new div to hold your document
            StringBuilder sb = new StringBuilder("<div id=\"xom\" style=\"font-family: 'Courier New', monospace; white-space: pre-wrap\"><pre>\n");
            // Create an array of strings with one string for each line in the document
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            Serializer writer = new Serializer(bout, "UTF-8");
            writer.setIndent(4);
            writer.write(document);
            writer.flush();
            String xomString = bout.toString("UTF-8");
            String[] lines = xomString.split(writer.getLineSeparator());
            for (int i = 0; i < lines.length; i++) {
                sb.append(convertLine(lines[i]));
            }
            sb.append("</pre></div>\n");
        } catch (IOException ex) {
            // handle the error
        }
        return sb.toString();
    }

    private String convertLine(String s) {
        // wrap the line in a code tag
        StringBuilder sb = new StringBuilder("<code>");
        // Remove trailing whitespace
        Pattern trailingWhiteSpace = Pattern.compile("[ \t\n\f\r]+$");
        Matcher m = trailingWhiteSpace.matcher(s);
        sb.append(m.replaceAll(""));
        // Change all angle brackets "<" and ">"
        sb.append(line.replaceAll(">", "&gt;").replaceAll("<", "&lt;"));
        sb.append("</code>\n");
        return sb.toString();
    }
Wee Shetland
  • 955
  • 8
  • 18