java中使用xsd验证xml

1. 首先要导入包,axiom包请到apache上下载

 

2. xsd和xml 文件放在工程 bin路径下即可。

 

 

package xmlValidate;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.xml.sax.SAXException;

public class SchemaValidate {

    /**
     * Validate the XML file with XML Schema file
     *
     * XSD和XML文件放在工程的bin路径下
     * @throws SAXException
     * @throws IOException
     */
    public static boolean validate(String schemaLocaltion, OMElement request)
                  throws SAXException, IOException
    {
           //获取Schema工厂类
           //这里的XMLConstants.W3C_XML_SCHEMA_NS_URI的值就是://http://www.w3.org/2001/XMLSchema
           SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
           // Schema实例
           Schema schema = null;
           //获取XSD文件,以流的方式读取到Source中
           //XSD文件的位置相对于类文件位置
           Source schemaSource = new StreamSource(SchemaValidate.class.getResourceAsStream(schemaLocaltion));
           //实例化Schema对象
           schema = factory.newSchema(schemaSource);
           //这里是将一个DOM树对象转换成流对象,以便对DOM树对象验证
           //如果是对XML文件进行验证,用FileInputStream即可
           String input = request.toString();
           ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes("UTF-8"));
           // 获取验证器,验证器的XML Schema源就是之前创建的Schema
           Validator validator = schema.newValidator();
           Source source = new StreamSource(bais);
           // 执行验证
           try
           {
               validator.validate(source);
               return true;
           }
           catch(Exception ex)
           {
               return false;
           }
    }

    /**
     * get OMElement soap request from specified XML file.
     *
     * @param request
     * @return
     * @throws FileNotFoundException
     * @throws XMLStreamException
     * @throws FactoryConfigurationError
     */
    public static OMElement getRequest(String filePath)
            throws FileNotFoundException, XMLStreamException,
            FactoryConfigurationError {
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(SchemaValidate.class.getResourceAsStream(filePath));
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        OMElement requestMessage = builder.getDocumentElement();
        return requestMessage;
    }

    public static void main(String[] args) //throws SAXException, IOException,
            //XMLStreamException, FactoryConfigurationError
    {
        try
        {
//            if(validate("/customer.xsd", getRequest("/customer.xml")))
//            {
//                System.out.println("customer.xml格式良好");
//            }else
//            {
//                System.out.println("customer.xml格式有误,请检查!");
//            }
            if(validate("/customer.xsd", getRequest("/customer_err.xml")))
            {
                System.out.println("customer_err.xml格式良好");
            }else
            {
                System.out.println("customer_err.xml格式有误,请检查!");
            }
        }
        catch(Exception ex)
        {
            System.out.println("文件格式有误,请检查!");
        }

    }
}

你可能感兴趣的:(java中使用xsd验证xml)