基于在内存中预先创建文档的模板和其他方法可能会对生成的文档大小施加一定限制。
同时,基于SAX处理程序和默认XSLT转换器的简单可靠的即时写入纯HTML创建方法存在,后者具有HTML输出的固有能力:
String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory saxFactory =
(SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);
Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
tHandler.startElement("", "", "html", new AttributesImpl());
tHandler.startElement("", "", "head", new AttributesImpl());
tHandler.startElement("", "", "title", new AttributesImpl());
tHandler.characters("Hello".toCharArray(), 0, 5);
tHandler.endElement("", "", "title");
tHandler.endElement("", "", "head");
tHandler.startElement("", "", "body", new AttributesImpl());
tHandler.startElement("", "", "p", new AttributesImpl());
tHandler.characters("5 > 3".toCharArray(), 0, 5);
tHandler.endElement("", "", "p");
tHandler.endElement("", "", "body");
tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();
请注意,XSLT转换器会为您减轻转义特殊字符(如
>
)的负担,因为它会自行处理这些问题。
而且,将SAX方法(例如
startElement()
和
characters()
)封装成更方便的形式也很容易。
String template = FileUtils.readFileToString(htmlTemplateFile); String title = "New Page"; String body = "This is Body"; String htmlString = MessageFormat.format(template, title, body);
然后,template
应该包含{0}
用于title
和{1}
用于body
。 - Sergey Ushakov