近日在使用 DOM4J 的时候,遇到一个问题,现在有两个解决方法,先记下来,以便日后使用。
问题:对一个 XML 文件进行读写操作,但是发现当文件存在的时候,使用DOM4J读进来的时候,生成的 Document 对象会根据 DTD 里的定义,追加了一些 default 属性(实际不需要)。而且在读取的时间被延长。
有一个 XML 文件如下:<o:p></o:p>
xml 代码
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
-
- <beans>
- ....
- </beans>
使用 DOM4J 的读取文件的一般性写法:<o:p></o:p>
java 代码
- SAXReader reader = new SAXReader(false);
- document = reader.read(file);
- root = document.getRootElement();
对象 document 里的节点会被自动追加 DTD 里的定义的 default 属性,只有新增加的节点不受影响,如下。而且,如果文件的操作时间被延长。
xml 代码
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
-
- <beans default-lazy-init="false" default-autowire="no" default-dependency-check="none">
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase" lazy-init="default" autowire="default" dependency-check="default"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase"/>
- <bean id="OperateXmlByDom4jTestCase" class="test.OperateXmlByDom4jTestCase"/>
- </beans>
<o:p></o:p>
为了不让生成我们不需要的 default 属性和缩短文件的操作时间,我们可以调用 SAXReader.setFeature 方法来改变 DOM4J 的行为,片断代码如下:<o:p></o:p>
java 代码
-
- saxReader.setFeature(
- Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE,
- false);
关于更多的 Feature 请参考 com.sun.org.apache.xerces.internal.impl.Constants<o:p></o:p>
以下为片断代码:<o:p></o:p>
java 代码
-
-
-
- public static final String XERCES_FEATURE_PREFIX = "http://apache.org/xml/features/";
-
-
- public static final String SCHEMA_VALIDATION_FEATURE = "validation/schema";
-
-
- public static final String SCHEMA_NORMALIZED_VALUE = "validation/schema/normalized-value";
-
-
- public static final String SCHEMA_ELEMENT_DEFAULT = "validation/schema/element-default";
-
-
- public static final String SCHEMA_FULL_CHECKING = "validation/schema-full-checking";
-
-
- public static final String SCHEMA_AUGMENT_PSVI = "validation/schema/augment-psvi";
-
-
- public static final String DYNAMIC_VALIDATION_FEATURE = "validation/dynamic";
-
-
- public static final String WARN_ON_DUPLICATE_ATTDEF_FEATURE = "validation/warn-on-duplicate-attdef";
-
-
- public static final String WARN_ON_UNDECLARED_ELEMDEF_FEATURE = "validation/warn-on-undeclared-elemdef";
-
-
- public static final String WARN_ON_DUPLICATE_ENTITYDEF_FEATURE = "warn-on-duplicate-entitydef";
-
-
- public static final String ALLOW_JAVA_ENCODINGS_FEATURE = "allow-java-encodings";
-
-
- public static final String DISALLOW_DOCTYPE_DECL_FEATURE = "disallow-doctype-decl";
-
-
- public static final String CONTINUE_AFTER_FATAL_ERROR_FEATURE = "continue-after-fatal-error";
-
-
- public static final String LOAD_DTD_GRAMMAR_FEATURE = "nonvalidating/load-dtd-grammar";
-
-
- public static final String LOAD_EXTERNAL_DTD_FEATURE = "nonvalidating/load-external-dtd";
-
-
- public static final String DEFER_NODE_EXPANSION_FEATURE = "dom/defer-node-expansion";
-
-
- public static final String CREATE_ENTITY_REF_NODES_FEATURE = "dom/create-entity-ref-nodes";
-
-
- public static final String INCLUDE_IGNORABLE_WHITESPACE = "dom/include-ignorable-whitespace";
-
-
- public static final String DEFAULT_ATTRIBUTE_VALUES_FEATURE = "validation/default-attribute-values";
-
-
- public static final String VALIDATE_CONTENT_MODELS_FEATURE = "validation/validate-content-models";
-
-
- public static final String VALIDATE_DATATYPES_FEATURE = "validation/validate-datatypes";
-
-
- public static final String NOTIFY_CHAR_REFS_FEATURE = "scanner/notify-char-refs";
-
- /** Notify built-in (&, etc.) references feature (scanner/notify-builtin-refs"). */
- public static final String NOTIFY_BUILTIN_REFS_FEATURE = "scanner/notify-builtin-refs";
-
-
- public static final String STANDARD_URI_CONFORMANT_FEATURE = "standard-uri-conformant";
-
-
-
-
-
-
- public static final String PARSER_SETTINGS = "internal/parser-settings";
-
-
- public static final String XINCLUDE_AWARE = "xinclude-aware";
-
-
- public static final String IGNORE_SCHEMA_LOCATION_HINTS = "validation/schema/ignore-schema-location-hints";
-
-
-
-
-
-
- public static final String CHANGE_IGNORABLE_CHARACTERS_INTO_IGNORABLE_WHITESPACES =
- "validation/change-ignorable-characters-into-ignorable-whitespaces";
除通过上面的 SAXReader.setFeature 文件之外 ,我们还可以通过自己的 EntityResolver 来解决这个问题。<o:p></o:p>
PS:这个方法是从凝香小筑的BLOG里的一编主题是:Do not resolve DTD files when dom4j read xml file 的文章里看到的。地址:http://blog.csdn.net/lessoft/archive/<st1:chsdate w:st="on" isrocdate="False" islunardate="False" day="20" month="6" year="2007">2007/06/20</st1:chsdate>/1659579.aspx<o:p></o:p>
代码片断如下:<o:p></o:p>
java 代码
- saxReader.setEntityResolver(new EntityResolver() {
-
- String emptyDtd = "";
-
- ByteArrayInputStream bytels = new ByteArrayInputStream(emptyDtd.getBytes());
-
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException, IOException {
- return new InputSource(bytels);
- }
- });
<o:p> </o:p>
完整的代码如下:<o:p></o:p>
java 代码
- package test;
-
- import java.io.BufferedWriter;
- import java.io.ByteArrayInputStream;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
-
- import junit.framework.TestCase;
-
- import org.dom4j.Document;
- import org.dom4j.DocumentHelper;
- import org.dom4j.Element;
- import org.dom4j.io.OutputFormat;
- import org.dom4j.io.SAXReader;
- import org.dom4j.io.XMLWriter;
- import org.dom4j.tree.DefaultDocumentType;
- import org.xml.sax.EntityResolver;
- import org.xml.sax.InputSource;
- import org.xml.sax.SAXException;
-
- import com.sun.org.apache.xerces.internal.impl.Constants;
-
-
-
-
-
-
- public class OperateXmlByDom4jTestCase extends TestCase {
-
-
-
-
-
- public void testWriteXml() throws Exception {
- XmlFileOperation operation = new XmlFileOperation();
- operation.writer(new SAXReaderWrapper() {
- public void operation(SAXReader saxReader) throws Exception {
-
- }
- });
- }
-
-
-
-
-
- public void testWriteXmlSetFeature() throws Exception {
- XmlFileOperation operation = new XmlFileOperation();
- operation.writer(new SAXReaderWrapper() {
- public void operation(SAXReader saxReader) throws Exception {
-
- saxReader.setFeature(
- Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE,
- false);
- }
- });
- }
-
-
-
-
-
- public void testWriteXmlEntityResolver() throws Exception {
- XmlFileOperation operation = new XmlFileOperation();
- operation.writer(new SAXReaderWrapper() {
- public void operation(SAXReader saxReader) throws Exception {
- saxReader.setEntityResolver(new EntityResolver() {
-
- String emptyDtd = "";
-
- ByteArrayInputStream bytels = new ByteArrayInputStream(emptyDtd.getBytes());
-
- public InputSource resolveEntity(String publicId,
- String systemId) throws SAXException, IOException {
- return new InputSource(bytels);
- }
- });
- }
- });
- }
-
- /** */
- protected interface SAXReaderWrapper {
-
- /** operation {@link SAXReader} */
- void operation(SAXReader saxReader) throws Exception;
-
- }
-
- /**
- * when the target file was existed, read and append the new element.
- * else, create a new xml file and add the new element.
- */
- protected class XmlFileOperation {
-
- /** target file */
- private File file;
-
- public XmlFileOperation() {
- // target file
- file = new File("d:\\spring.xml");
- }
-
- /**
- * Write xml file
- * @param wrapper
- * @throws Exception
- * @see {@link SAXReaderWrapper}
- */
- public void writer(SAXReaderWrapper wrapper) throws Exception {
- try {
- Document document = null;
- Element root = null;
-
- // read the xml file if target file was existed
- if (file.exists()) {
- SAXReader reader = new SAXReader(false);
-
- wrapper.operation(reader);
-
- document = reader.read(file);
- root = document.getRootElement();
- // if the target file was not existed, create a new one
- } else {
- document = DocumentHelper.createDocument();
- document.setDocType(new DefaultDocumentType("beans",
- "-
- "http:
- root = document.addElement("beans");
- }
- // create the element under the root element
- root.addElement("bean")
- .addAttribute("id", "OperateXmlByDom4jTestCase")
- .addAttribute("class", "test.OperateXmlByDom4jTestCase");
-
-
- writer(document);
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- }
- }
-
- protected void writer(Document document) throws Exception {
- XMLWriter xmlWriter = null;
- try {
- final OutputFormat format = OutputFormat.createPrettyPrint();
- xmlWriter = new XMLWriter(new BufferedWriter(new FileWriter(file)), format);
- xmlWriter.write(document);
- } finally {
- if (null != xmlWriter) {
- xmlWriter.flush();
- xmlWriter.close();
- }
- }
- }
- }
- }