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