【问题标题】:how to return serialized XML file (XOM document), so that i can display it in browser?如何返回序列化的 XML 文件(XOM 文档),以便我可以在浏览器中显示它?
【发布时间】:2015-04-14 07:17:31
【问题描述】:

这会在控制台上打印出我的 xml 文档,并带有漂亮的打印效果。

//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);

我需要返回相同的xml文档,以便在浏览器中显示。

【问题讨论】:

    标签: xml xom


    【解决方案1】:

    我的一个应用程序有完全相同的要求。您可以通过获取序列化的 XOM 文档、将其包装在代码标签中并转义尖括号来完成此操作。下面的示例代码显示了一种方法:

         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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 2020-11-08
      • 2021-02-25
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多