我想解析声明HTML 4.01 Doctype的xml文件。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
[...]
</html>
我使用Stax和XMLResolver来加载本地dtd
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setXMLResolver(new LocalXmlResolver());
xmlOutputFactory = XMLOutputFactory.newInstance();
xmlOutputFactory.createXMLEventWriter(...)
private static final Map<String, String> DTDS = new HashMap<String, String>(){{
// XHTML 1.0 DTDs
put("-//W3C//DTD XHTML 1.0 Strict//EN", "xhtml1-strict.dtd");
put("-//W3C//DTD XHTML 1.0 Transitional//EN", "xhtml1-transitional.dtd");
put("-//W3C//DTD XHTML 1.0 Frameset//EN", "xhtml1-frameset.dtd");
put("-//W3C//DTD HTML 4.01//EN", "strict.dtd");
put("-//W3C//DTD HTML 4.01 Transitional//EN", "loose.dtd");
put("-//W3C//DTD HTML 4.01 Frameset//EN", "frameset.dtd");
}};
private static final class LocalXmlResolver implements XMLResolver {
@Override
public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException {
Object result = null;
String path = XHTML_DTD_PATH + DTDS.get(publicID);
if (StringUtils.isNotBlank(path)) {
result = getClass().getClassLoader().getResourceAsStream(path);
}
return result;
}
}
我从(w3c web site)检索了dtd。但我必须更改此文件以删除节点中的所有注释,如下所示:
<!ENTITY % ContentType "CDATA"
-- media type, as per [RFC2045]
-->
<!ENTITY % ContentType "CDATA">
但即使经过这些修改,我仍然有这个错误:
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[184,11]
Message: The element type is required in the element type declaration.
[...]
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[184,11]
Message: The element type is required in the element type declaration.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598)
at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(XMLEventReaderImpl.java:83)
在dtd文件中的,第184行是:
<!ELEMENT (%fontstyle;|%phrase;) - - (%inline;)* >
任何想法?
由于
答案 0 :(得分:2)
HTML是一种SGML语言,因此它有一个SGML DTD。您可以在此处找到有关SGML的更多信息:http://validator.w3.org/docs/sgml.html
SGML与XML略有不同,因此XML解析器无法解析它也就不足为奇了。
主要的例子是:
实体声明中的注释(用双连字符分隔: - 这是注释 - )在SGML DTD中是允许的,而不在XML DTD上。
如需更多信息,请点击http://www.w3.org/TR/NOTE-sgml-xml-971215#null
尽管如此,您无法通过创建自己的XMLResolver
来禁用特定DTD的DTD解析xmlInput = XMLInputFactory.newInstance();
xmlInput.setXMLResolver(new XMLResolver() {
@Override
public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException {
...
// Disable dtd validation
if ("The public id you except".equals(publicId)) {
return IOUtils.toInputStream("");
}
...
}
});
对于html解析器,请将http://jtidy.sourceforge.net/或http://jsoup.org/视为解决方案