XMLUtil源文件:
package com.lovo.util;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class XMLUtil {
public static Document readXml(String xmlFile) throws DocumentException
{
SAXReader reader = new SAXReader();
reader.setValidation(true);// 是否验证xml文件内的dtd
Document doc = null;
doc = reader.read(XMLUtil.class.getResourceAsStream(xmlFile));
return doc;
}
}
TestXMLUtil.java源文件
package com.lovo.test;
import org.dom4j.Document;
import com.lovo.util.XMLUtil;
public class TestXMLUtil {
public static void test1(){
Document doc = null;
try {
doc = XMLUtil.readXml("/com/lovo/xml/stu1.xml");
System.out.println(doc.asXML());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
test1();
}
}
stu1.xml文件:
<?xml version="1.0" encoding="gb2312"?> <!DOCTYPE lovo SYSTEM "bin/com/lovo/xml/rule.dtd"> <lovo> <class1 /> </lovo>
注意在DOCTYPE中限制xml文件中根节点为:lovo 。
rule.dtd文件:
<!ELEMENT lovo (class*) > <!ELEMENT class EMPTY >
现在执行,会因为stu1.xml使用了未定义的class1节点,所以会报错:
Error on line 4 of document : Element type "class1" must be declared. Nested ex
ception: Element type "class1" must be declared.
验证成功。