Does anyone know how to generate an HTMLDocument object programmatically in Java without resorting to generating a String externally and then using HTMLEditorKit#read to parse i
When dealing with XHTML, I have had much success using Java 6's XMLStreamWriter interface.
OutputStream destination = ...;
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xml = outputFactory.createXMLStreamWriter(destination);
xml.writeStartDocument();
xml.writeStartElement("html");
xml.writeDefaultNamespace("http://www.w3.org/1999/xhtml");
xml.writeStartElement("head");
xml.writeStartElement("title");
xml.writeCharacters("The title of the page");
xml.writeEndElement();
xml.writeEndElement();
xml.writeEndElement();
xml.writeEndDocument();
You can use any decent xml library like JDom or Xom or XStream. Html is just a special case of XML.
Or, you can use one of the existing templating engines for server side java like jsp or velocity.
It appears that you can accomplish what you are attempting using direct construction of HTMLDocument.BlockElement
and HTMLDocument.BlockElement
objects. Theses constructors have a signature that suggests direct use is possible, at least.
I would suggest examining the Swing sources in OpenJDK to see how the parser handles this, and derive your logic from there.
I would also suggest that this optimization may be premature, and perhaps this should be a speed-optimized replacement for a simpler approach (i.e. generating the HTML text) only introduced if this really does become a performance hotspot in the application.
Basically you can insert html into your HTMLDocument using one of the insert methods, insertBeforeEnd(), insertAfterEnd(), insertBeforeStart(), insertAfterStart(). You supply the method with the html you want to insert and the position in the document tree that you want the html inserted.
eg.
doc.insertBeforeEnd(element, html);
The HTMLDocument class also provided methods for traversing the document tree.
javax.swing.text.html has HTMLWriter
and HTMLDocument
class among others. I have not used them. I have used the HtmlWriter
in .Net and it does exactly what you want, but the java version may not work out to be the same.
Here is the doc: http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/text/html/HTMLWriter.html
Also, I can't imagine a StringBuilder
being slower than building with an object layer. It seems to me that any object oriented approach would have to build the object graph AND then produce the string. The main reason not to use raw strings for this stuff is that you are sure to get encoding errors as well as other mistakes that produce malformed documents.
Option 2: You could use your favorite XML api's and produce XHTML.
You may want to build some Element object with a render() method, and then assemble them in a tree structure; with a visit algorhytm you may then proceed to set the values and then render the whole thing.
PS: have you considered some templating engine like freemarker?