使用Java编程生成HTMLDocument [英] Programmatic HTMLDocument generation using Java

查看:118
本文介绍了使用Java编程生成HTMLDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何在Java中以编程方式生成HTMLDocument对象,而无需通过外部生成String,然后使用HTMLEditorKit#read来解析它?我要问的两个原因是:首先,我的HTML生成例程需要非常快,我假设将字符串解析为内部模型比直接构建此模型成本更高。第二,面向对象的方法可能会导致更简洁的代码。



我还应该提到,出于授权的原因,我不能诉诸使用任何与JVM一起提供的库。



谢谢,
Tom

$ b $一个面向对象的方法是使用一个叫做

的rel = noreferrer> ECS

这是相当简单的图书馆,并且没有变化多少年。然后,HTML 4.01规范也没有改变;)我使用了ECS,并认为它比仅使用Strings或StringBuffers / StringBuilders生成大型HTML片段要好得多。



小例子:

  Option optionElement = new Option(); 
optionElement.setTagText(bar);
optionElement.setValue(foo);
optionElement.setSelected(false);

optionElement.toString()

 < option value ='foo'> bar< / option> 

该库支持HTML 4.0和XHTML。首先困扰我的唯一的事情是,与XHTML版本相关的类的名称以小写字母开头:选项 input a tr 等等,这违背了最基本的Java约定。但是如果你想使用XHTML,那么你可以习惯这种方式;至少我做了,令人惊讶的快。

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 it? Two reasons I ask:

Firstly my HTML generation routine needs to be very fast and I assume that parsing a string into an internal model is more costly than directly constructing this model.

Secondly, an object-oriented approach would likely result in cleaner code.

I should also mention that, for licensing reasons, I can't resort to using any libraries other than those shipped with the JVM.

Thanks, Tom

解决方案

One object-oriented approach is to use a library called ECS.

It is quite simple library, and has not changed for ages. Then again, the HTML 4.01 spec has not changed either ;) I've used ECS and consider it far better than generating large HTML fragments with just Strings or StringBuffers/StringBuilders.

Small example:

Option optionElement = new Option();
optionElement.setTagText("bar");
optionElement.setValue("foo");
optionElement.setSelected(false);   

optionElement.toString() would now yield:

<option value='foo'>bar</option>

The library supports both HTML 4.0 and XHTML. The only thing that initially bothered me a lot was that names of classes related to the XHTML version started with a lowercase letter: option, input, a, tr, and so on, which goes against the most basic Java conventions. But that's something you can get used to if you want to use XHTML; at least I did, surprisingly fast.

这篇关于使用Java编程生成HTMLDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆