如何阻止HTMLWriter编写糟糕的HTML?(使用HTMLEditorKit)



以下是令人惊讶的行为。我创建了一个JTextPane,将其设置为使用HTMLEditorKit,并用有效的HTML填充它。但默认情况下,Java的HTMLWriter会创建无效的HTML。大多数项目都是正确序列化的,但img标签失去了结束斜杠,所以:

<img src="https://localhost:9443/ccm/service/com.ibm.team.workitem.common.internal.model.IImageContentService/processattachment/_7rfpIMXdEeGLRroh_7O2yQ/workflow/resolve.gif" alt="Resolved" border="0"/>

写为:

<img src="https://localhost:9443/ccm/service/com.ibm.team.workitem.common.internal.model.IImageContentService/processattachment/_7rfpIMXdEeGLRroh_7O2yQ/workflow/resolve.gif" alt="Resolved" border="0">

我对所有内容都使用默认值。为什么它不起作用,有什么简单的解决办法吗?

下面是一个代码片段:

    JTextPane editor = new JTextPane();
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    editor.setContentType("text/html");
    editor.setEditorKit(htmlKit);   
    editor.setText( '*<ADD SOME VALID HTML FROM A FILE>*'  );       
    HTMLDocument d = (HTMLDocument)editor.getDocument();
    StringWriter fw = new StringWriter();
    HTMLWriter aHTMLWriter = new HTMLWriter(fw,d);
    aHTMLWriter.write();
    String txt = fw.toString();
    //  Now  txt is not valid HTML ... eek!

遗憾的是,HTMLEditorKit只支持HTML3.2,因此不应该关闭img标记。因此,它的行为是"正确的"。

1999年发布了改进请求,因此可能很快就会实施。

实际上,它是有效的HTML,但不是有效的XHTML。据我所知,不可能让它输出XHTML。您可以使用正则表达式对输出进行后处理,或者像Freeplane在编写XHTMLWriter时那样扩展HTMLWriter。

最新更新