手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>程序设计>Java技术>列表

The way to dynamic validate xml against DTD

来源:互联网 作者:west263.com 时间:2008-02-23
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!
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); // never 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 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 your good luck.

上一篇: 在Java中读写Excel文件
下一篇: java初学者必读-经验总结

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!