我想解析声明 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 网站)检索了 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;)* >
任何想法 ?
谢谢