5

我在 JAVA 中有一些格式不正确的 xml (HTML) 数据,我使用了 JAXP Dom,但它抱怨。

问题是:有没有办法使用 JAXP 来解析这些文件?

我有一个包含数据的文件,例如:

<employee>
 <name value="ahmed" > <!-- note, this element is not closed, So it is not well-formed xml-->
</employee>
4

3 回答 3

8

您可以先尝试通过 jtidy API 运行您的文档 - 它能够将 html 转换为有效的 xhtml:http: //jtidy.sourceforge.net/howto.html

Tidy tidy = new Tidy();
tidy.setXHTML(true);
tidy.parse(......)...
于 2010-04-01T13:55:08.407 回答
8

您可以使用TagSoup。我使用它取得了巨大的成功。它与 Java XML API 完全兼容,包括 SAX、DOM、XSLT 和 StAX。例如,下面是我如何使用它来将 XSLT 转换应用于特别糟糕的 HTML:

public static void transform(InputStream style, InputStream data)
        throws SAXException, TransformerException {
    XMLReader reader =
        XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");
    Source input = new SAXSource(reader, new InputSource(data));
    Source xsl = new StreamSource(style);
    Transformer transformer =
        TransformerFactory.newInstance().newTransformer(xsl);
    transformer.transform(input, new StreamResult(System.out));
}
于 2010-04-01T13:58:26.210 回答
1

并不真地。JAXP 需要格式良好的标记。你考虑过Cyber​​neko HTML Parser吗?我们在我们的商店中使用它非常成功。

编辑:我看到你也想解析 XML。嗯.... Cyber​​neko 适用于 HTML,但我不知道其他人。它有一个标签平衡器,可以关闭一些标签,但我不知道你是否可以训练它识别不是 HTML 的标签。

于 2010-04-01T13:51:37.940 回答