如何让JTIdy使HTML文档格式良好?

Dav*_*ave 7 html java xml parsing jtidy

我正在使用JTidy v.r938.我正在使用此代码尝试清理页面...

final Tidy tidy = new Tidy();
tidy.setQuiet(false);
tidy.setShowWarnings(true);
tidy.setShowErrors(0);
tidy.setMakeClean(true);
Document document = tidy.parseDOM(conn.getInputStream(), null);
Run Code Online (Sandbox Code Playgroud)

但是当我解析这个URL - http://www.chicagoreader.com/chicago/EventSearch?narrowByDate=This+Week&eventCategory=93922&keywords=&page=1时,事情并没有得到清理.例如,页面上的META标签就像

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
Run Code Online (Sandbox Code Playgroud)

保持为

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
Run Code Online (Sandbox Code Playgroud)

而不是具有"</ META>"标签或显示为"<META http-equiv ="Content-Type"content ="text/html; 字符集= UTF-8 "/>".我通过将生成的JTidy org.w3c.dom.Document输出为String来确认这一点.

我能做些什么才能让JTidy真正清理页面 - 即使它格式良好?我意识到还有其他工具,但这个问题与使用JTIdy有关.

Pau*_*gas 6

如果要XML格式,则需要为Tidy指定几个标志

private String cleanData(String data) throws UnsupportedEncodingException {
    Tidy tidy = new Tidy();
    tidy.setInputEncoding("UTF-8");
    tidy.setOutputEncoding("UTF-8");
    tidy.setWraplen(Integer.MAX_VALUE);
    tidy.setPrintBodyOnly(true);
    tidy.setXmlOut(true);
    tidy.setSmartIndent(true);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes("UTF-8"));
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    tidy.parseDOM(inputStream, outputStream);
    return outputStream.toString("UTF-8");
}
Run Code Online (Sandbox Code Playgroud)

或者只是如果想要XHTML形式

Tidy tidy = new Tidy();
tidy.setXHTML(true);
Run Code Online (Sandbox Code Playgroud)

  • 我同时使用“ setXmlOut”和“ setXHTML”进行了尝试,但均未生成“ document = tidy.parseDOM(...)”返回的格式正确的文档。此外,JTidy还吐出了一条消息:“此文档中的错误必须先纠正,然后才能使用HTML Tidy生成整理的版本。” (3认同)