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);
}
# 1 楼答案
创建一个基础抽象类HTMLEntity。这将保存其中的文本和/或元素、样式等。添加一个方法toHtml(或使用toString)来生成HTML。添加方法以添加子对象
# 2 楼答案
html就是XML,因此使用DocumentBuilderFactory创建XMLDOM文档,然后用html元素填充它,最后将其写入流或磁盘文件是一种合乎逻辑的方法
或者使用内置的XSLT转换功能将XSLT表应用于现有的XML DOM对象或文件,以将其转换为HTML
哪一个更好取决于您的具体要求。第二,初始设置时需要做更多的工作,但灵活性和可重用性要高得多
# 3 楼答案
有两种方法可以实现这一点: 1) 使用ApacheVelocity模板将文件中的HTML标记与生成的数据合并,而不用担心使用纯代码构建HTML
2)使用现有模板并使用JSOUP(一个HTML DOM操纵库)进行操纵
我考虑用例,例如为电子邮件生成HTML,甚至PDF生成。p>
如果需要纯生成,请尝试查看https://code.google.com/p/gagawa/