如何申请本地DTD文件进行验证,以XML文件中的Java? [英] How to apply validation of local DTD file to xml file in java?
问题描述
我需要解析一串传入的XML文档,但它不包含DTD声明。目前,我解析使用SAX解析器,但没有DTD验证XML文档。现在,我想申请DTD验证。 DTD是由自己创造。我如何可以验证使用由我自己(SAX解析器)创建DTD的XML文件?我发现用变压器,但所有的DOM解析器一些教程。
I need to parse a bunch of incoming XML documents but it does not contain DTD declaration. Currently I am parsing xml documents using SAX Parser but without DTD validation. Now I want to apply DTD validation. DTD is created by myself. How can I validate an XML file using DTD created by myself (SAX parser) ? I found some tutorials using Transformer but all for DOM Parser.
如何使用SAX解析器,也将DTD验证解析XML文件。 任何帮助......
How to parse XML file using SAX Parser and also applying DTD validation. Any help....
推荐答案
下面是一个示例,我相信可以帮到你想要的:
Below is a sample that I believe could help to do what you want:
private void loadXML(Reader reader) throws ParserConfigurationException, SAXException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(true);
SAXParser parser = parserFactory.newSAXParser();
parser.parse(new InputSource(reader), new MyHandler());
}
private static class MyHandler
extends DefaultHandler {
private static final String PREFS_DTD_URI = "http://www.example.com/dtd/document.dtd";
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
if (systemId.equals(PREFS_DTD_URI)) {
InputSource is = new InputSource(new StringReader(PREFS_DTD)); // PREFS_DTD is a string containing actual DTD, any other Reader could be here
is.setSystemId(PREFS_DTD_URI);
return is;
}
// else use the default behaviour
return null;
}
}
这篇关于如何申请本地DTD文件进行验证,以XML文件中的Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!