The way to dynamic validate xml against DTD

    Although the apache digester is popular today and also benefit us a lot,  but sometimes we still need to validate or parse the xml base on the DTD,  for the static validate/parse (most of the case, it is the procedure of reading a configuration file of the Web Application),  it is really easy to do, we can just specify the path of the xml and let the SAX or DOM do rest things for us.  But what if you need to validate the xml dynamiclly?(Eg, you received a xml from others and you need to specify the different DTD base on the different case, that is common in a J2EE project)
 
    The following API will handle with such case. For the SAX
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true); // don't forgot this
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    reader.setEntityResolver(##you own error handler##);
    reader.setErrorHandler(##you own error handler##);

     For the DOM
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance()
     factory.setValidating(true); // never forgot this
     DocumentBuilder builder = factory.newDocumentBuilder();
     builder.setEntityResolver((##you own error handler##););
     builder.setErrorHandler((##you own error handler##););


     Be very awear of handling the error correctly in your Handler class, Never Try To Use The DefaultHandler. you may drop into the trap. look at the java api of the org.xml.sax...DefaultHandler of error

public void error(SAXParseException e) throws SAXException
receive notification of a recoverable parser error. The default implementation does nothing. Application writers may override this method in a subclass to take specific actions for each error, such as inserting the message in a log file or printing it to the console. Specified by: error in interface ErrorHandler you can never image that the sun provide us a api that skip the error handling. that is stupid in most of the case I think. actually, I spend to much time on it today. hope you good luck.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值