java 使用xsd文件 校验 xml文件

1,工具类

package com.word.chain.prj.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;


public class XMLValidateUtils {

	/**
	 * @param xmlFile  xml字符串
	 * @param xsdFilePath  xsd 文件的全路径
	 * @return
	 */
	public static String validateXMLWithXSD(String xmlFile, String xsdFilePath) {
		XMLErrorHandler errHandler=null;
		try {
			Reader xmlReader = new BufferedReader(new StringReader(xmlFile));
			Reader xsdReader = new BufferedReader(new FileReader(xsdFilePath));
			Source xmlSource = new StreamSource(xmlReader);
			Source xsdSource = new StreamSource(xsdReader);
			SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Schema schema = factory.newSchema(xsdSource);
			XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(xmlSource);
			Validator validator = schema.newValidator();
			errHandler = new XMLErrorHandler(reader);
			validator.setErrorHandler(errHandler);
			validator.validate(new StAXSource(reader));
			return errHandler.getErrorElement();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
1.1---上文提到的XMLErrorHandler 类

package com.word.chain.prj.utils;

import javax.xml.stream.XMLStreamReader;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * @author Administrator
 * 
 * XML错误处理器,用于获得XML中哪一个元素标签的数据有误
 *
 */
public class XMLErrorHandler implements ErrorHandler {
	private String errorElement = null;
	private XMLStreamReader reader;
	public XMLErrorHandler(XMLStreamReader reader) {
		this.reader = reader;
	}
	@Override
	public void warning(SAXParseException e) throws SAXException {
		fatalError(e);
	}
	@Override
	public void error(SAXParseException e) throws SAXException {
		fatalError(e);
	}
	@Override
	public void fatalError(SAXParseException e) throws SAXException {
        String lement = reader.getLocalName();
        String msg= e.getMessage();
        this.errorElement=lement+":"+msg;
	}
	public String getErrorElement() {
		return errorElement;
	}
	public void setErrorElement(String errorElement) {
		this.errorElement = errorElement;
	}

}

2.被校验的xml文件内容

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <name>1</name>
    <phone>12312312</phone>
    <suns>
        <name>1211111</name>
        <sex>1</sex>
    </suns>
</root>

3.下图为xml校验使用的 xsd 文件



已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页