I want to create a HTML document in Java code, how can I do that effectively with Java SE 1.7, without relying on third party libs?
Goal would be to not have to manually append html strings together and get some help with keeping the html valid.
I want to create a HTML document in Java code, how can I do that effectively with Java SE 1.7, without relying on third party libs?
Goal would be to not have to manually append html strings together and get some help with keeping the html valid.
html is just XML, so using a DocumentBuilderFactory to create an XML DOM Document, then populating it with your HTML elements, and finally writing it out to a Stream or disk file is a logical way to do this.
Or use the built in XSLT transformation functionality to apply a XSLT sheet to an existing XML DOM object or file to turn that into HTML.
Which would be preferable depends on your exact requirements. Second is a bit more work to set up initially but a lot more flexible and reusable.
Create a base abstract class, HTMLEntity. This will hold the text and/or elements inside it, style and so on. Add a method, toHtml(or use toString) to generate the HTML. Add a method to add a child.
abstract class HtmlEntity {
private List<HtmlEntity> children;
private String tag;
private boolean canHaveChildren; // for tags like img, hr, br ...
private boolean canSelfClose; // for tags like img, hr, br ...
// you get the idea, add a list of classes, an optional id, even a XPath string ...
public String toString() {
StringBuilder sb = new StringBuilder("<").append(tag)
// for each property, sb.append(key).append("=").append(value);
// for each child, sb.append(child.toString());
// if canSelfClose sb.append("/>"); else sb.append("</").append(tag).append(">");
}
// override this in subclasses, be more restrictive, i.e. for ULs you should have addChild(LiEntity child);
public boolean addChild(HtmlEntity child);
}
There are couple of ways to approach this: 1) Use Apache Velocity templates to merge HTML markup in a file with data generated rather than worrying about HTML construction using sheer code
2) Use a existing template and manipulate using JSOUP (a HTML DOM manipulation library)
I consider the use cases such as generating HTML for emails, or even PDF generation.
If pure generation is required, try looking at https://code.google.com/p/gagawa/