Java中对XML文件的校验
Java中使用dtd校验xml文件:
1.定义一个校验类CheckXML类:
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class CheckXML(){
public Doucment getCheckXML(){
List<studentUAO> result = new ArrayList<>();
// 使用Java的类加载器,查找类路径下的资源文件。
// 1.获取任意的Class类型的对象,类名.class就可以返回一个Class对象。
Class<?> clazz = Teststudent.class;
// 2.调用getResourceAsStream(arg0)得到输入流。
// 从类路径的根目录查找名为book.xml的文件。
// 自动在所有的类路径下面查找名为student.xml的文件,找到第一个就马上返回,不会继续找。
URL url = clazz.getResource("./student.xml");
//下面是输出student.xml文件的根目录
System.out.println(url);
InputStream in = url.openStream();
// 1.创建DocumentBuilderFactory
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
// 开启验证!
builderFactory.setValidating(true);
// 2.利用DocumentBuilderFactory创建DocumentBuilder
DocumentBuilder builder = builderFactory.newDocumentBuilder();
// 3.使用EntityResolver告诉XML解析器DTD文件在哪里!
// 同样在当前类的类路径下面,查找student.dtd文件
builder.setEntityResolver(new EntityResolver(){
@Override
public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException {
InputStream dtdStream = clazz.getResourceAsStream("./student.dtd");
InputSource source = new InputSource(dtdStream);
return source;
}
});
// 4.为了能够得到准确的解析验证信息,必须提供一个ErrorHandler
MyErrorHandler eh = new MyErrorHandler();
builder.setErrorHandler(eh);
if(eh.isSucceed()){
System.out.println("解析成功!");
// 5.执行解析
// 底层使用SAX方式读取XML内容,这样读取的性能比较好
Document doc = builder.parse(in);
return doc;
}else{
System.out.println("解析失败!");
return null;
}
}
static class MyErrorHandler implements ErrorHandler {
private Integer Errorcount = 0;
@Override
public void error(SAXParseException arg0) throws SAXException {
System.out.println("出现错误!");
arg0.printStackTrace(System.out);
Errorcount++; }
@Override
public void fatalError(SAXParseException arg0) throws SAXException {
System.out.println("出现致命的错误!");
arg0.printStackTrace(System.out);
Errorcount++; }
@Override
public void warning(SAXParseException arg0) throws SAXException {
System.out.println("出现警告!");
arg0.printStackTrace(System.out); }
//判断是否解析成功!
public boolean isSucceed(){ if(Errorcount == 0){ return true; } return false; } }
}
1.2dom4j使用dtd校验xml:
// 1.创建SAXReader SAXReader reader = new SAXReader();
// 2.打开验证 reader.setValidation(true);
// 3.设置EntityResolver,在DOM4j里面,默认能够找到相同目录下的dtd文件 /
/ 提供setEntityResolver的原因,主要是解决:如果XML里面声明的dtd文件和实际的dtd文件的名字不同的时候,能够正确找到dtd
reader.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
URL dtdURL = cla.getResource("./students.dtd");
InputStream dtdStream = dtdURL.openStream();
InputSource source = new InputSource(dtdStream);
return source; } });
// 4.读取XML,生成Document对象
Document document = reader.read(url);
==============================================
Java使用schame校验xml文件:
2.1创建一个ValidationXM类:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class ValidationXML {
public static void getValidationXML() throws SAXException, IOException {
URL url = ValidationXML.class.getResource("book.xsd");
// 读取Schema文件
Schema s = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(url);
// 创建验证器
Validator v = s.newValidator();
// 对输入流进行验证
InputStream in = ValidationXML.class.getResourceAsStream("/book.xml");
StreamSource source = new StreamSource(in);
v.validate(source);
// 验证没有报错再去读取
//........................parse();
} }
3.使用dom4j:需要导两个包:dom4j.jar,jaxen-1.1-beta-6.jar。
import java.io.IOException;
import java.io.InputStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ValidatingDom4j {
public static void main(String[] args) throws DocumentException,
SAXException {
SAXReader reader = new SAXReader();
// 打开验证
reader.setValidation(true);
//验证指定的输入。
reader.setFeature("http://apache.org/xml/features/validation/schema", true);
// 找到xsd文件的位置 reader.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
InputStream in = ValidatingDom4j.class .getResourceAsStream("book.xsd");
InputSource source = new InputSource(in);
return source; }
});
InputStream in = ValidatingDom4j.class.getResourceAsStream("book.xml");
Document doc = reader.read(in); } }