java 检证xml文件,如何申请本地DTD文件进行验证,以XML文件中的Java?

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.

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;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值