dom4j解析xml⽂件时忽略DOCTYPE标签
利⽤dom4j读取xml配置⽂件时,如果⽂件中出现DOCTYPE标签,可能会在read时读取异常:
Document document = ad(file);
导致⽂件读取失败,如下:
Exception in thread "main" org.dom4j.DocumentException: Error on line 1 of document /testng-1.0.dtd : ⽂档类型声明包含或指向的标记声明必须格 at org.dom4j.ad(SAXReader.java:482)
at org.dom4j.ad(SAXReader.java:264)
at com.sinosoft.listest.service.impl.ProduceXmlImpl.updateAllTestngXml(ProduceXmlImpl.java:32)
at com.sinosoft.listest.service.ProduceXml.updateAllTestngXml(ProduceXml.java:16)
at com.sinosoft.listest.utils.PrepareDateUtil.updateAllTestngXml(PrepareDateUtil.java:38)
at com.sinosoft.listest.Test.main(Test.java:12)
Nested exception:
at s.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at s.internal.portError(XMLErrorReporter.java:441)
at s.internal.portError(XMLErrorReporter.java:368)
at s.internal.portFatalError(XMLScanner.java:1436)
at s.internal.impl.XMLDTDScannerImpl.scanDecls(XMLDTDScannerImpl.java:2002)
at s.internal.impl.XMLDTDScannerImpl.scanDTDExternalSubset(XMLDTDScannerImpl.java:305)
at s.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1177)
at s.internal.impl.(XMLDocumentScannerImpl.java:1050)
at s.internal.impl.(XMLDocumentScannerImpl.java:964)
at s.internal.(XMLDocumentScannerImpl.java:606)
at s.internal.(XMLNSDocumentScannerImpl.java:117)
at s.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at s.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at s.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at s.internal.parsers.XMLParser.parse(XMLParser.java:141)
at s.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at s.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at org.dom4j.ad(SAXReader.java:465)
at org.dom4j.ad(SAXReader.java:264)
at com.sinosoft.listest.service.impl.ProduceXmlImpl.updateAllTestngXml(ProduceXmlImpl.java:32)
at com.sinosoft.listest.service.ProduceXml.updateAllTestngXml(ProduceXml.java:16)
使用dom4j解析xml文件
at com.sinosoft.listest.utils.PrepareDateUtil.updateAllTestngXml(PrepareDateUtil.java:38)
at com.sinosoft.listest.Test.main(Test.java:12)
Process finished with exit code 1
特别是l时,如果不添加则⽆法正常运⾏程序。
<!DOCTYPE suite SYSTEM "/testng-1.0.dtd" >
百度实验了各种解决⽅案都⽆法解决,最后终于到了⼀种适⽤的忽略dtd⽂件的⽅法(查询的另外⼏种统统未解决),贴上解决的代码以
供参考:
//获得⽂件
File file = new File(filePath);
//利⽤dom4j读取xml
SAXReader reader = new SAXReader();
//忽略dtd⽂件校验
reader.setValidation(false);
reader.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())); }
});
完美解决,以供参考谢谢。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论