java中使用xsd驗證xml

來源:互聯網
上載者:User

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("檔案格式有誤,請檢查!");
        }

    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.