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("文件格式有误,请检查!");
        }

    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值