Dom4j知识集锦
如何禁止加载XSD和DTD
1 2 |
SAXReader reader = new SAXReader( true ); reader.setFeature( Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false ); |
DTD验证,无法联网时报错
通过指定本地的DTD文档来解决:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
SAXReader reader = new SAXReader( true ); reader.setEntityResolver( new EntityResolver() { public InputSource resolveEntity( String publicId, String systemId ) { if ( publicId.equals( "-//Hibernate/Hibernate Mapping DTD 3.0//EN" ) ) { InputStream in = getClass().getResourceAsStream( "/hibernate-mapping-3.0.dtd" ); return new InputSource( in ); } return null; } } ); |
使用JAXP来进行XSD验证
1 2 3 4 |
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( XSD_FILE_PATH ); javax.xml.validation.SchemaFactory factory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); new StreamSource( is ) ).newValidator(); validator.validate( new StreamSource( new StringReader( xml ) ) ); |
Dom4j如何格式化XML输出
1 2 3 4 5 6 7 8 9 10 |
StringWriter sw = new StringWriter(); XMLWriter writer = new XMLWriter( sw, OutputFormat.createPrettyPrint() ); try { writer.write( doc ); } catch ( IOException e ) { // impossible } |
如何使用XPath解析带名字空间的XML
1 2 3 4 5 6 7 |
SAXReader reader = new SAXReader(); Map<String, String> nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put( "beans", "http://www.springframework.org/schema/beans" ); reader.getDocumentFactory().setXPathNamespaceURIs( nameSpaceMap ); Document doc = reader.read( new ClassPathResource( APP_CTX_FILE_NAME ).getInputStream() ); Element e = (Element) doc.getRootElement().selectSingleNode("beans:bean[@id='canaryConfig']/beans:property[@name='baseDir']" ); bd = e.attributeValue( "value" ); |
Dom4j访问者模式中,删除节点导致NullPointerException
报错:java.lang.NullPointerException at org.dom4j.tree.AbstractElement.accept(AbstractElement.java:208)
解决:在访问者中记录需要删除的节点,访问结束后一起删除。
Leave a Reply