两种方法:
1。 使用SAX解析:
[java]
/***
* @param xmlPath – XML文件路径
* @param schemaPath – Schema文件路径
*/
public void saxValidation(String xmlPath, String schemaPath){
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
saxParserFactory.setValidating(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
saxParser.setProperty(“http://java.sun.com/xml/jaxp/properties/schemaLanguage”, “http://www.w3.org/2001/XMLSchema”);
saxParser.setProperty(“http://java.sun.com/xml/jaxp/properties/schemaSource”, schemaPath);
DefaultHandler handler = new DefaultHandler();
saxParser.parse(xmlPath, handler);
} catch(SAXException exc) {
exc.printStackTrace();
}
}
[/java]
2。 使用DOM解析:
[java]
/***
* @param xmlPath – XML文件路径
* @param schemaPath – Schema文件路径
*/
public void domValidation(String xmlPath, String schemaPath){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
docBuilderFactory.setValidating(true);
docBuilderFactory.setAttribute(“http://java.sun.com/xml/jaxp/properties/schemaLanguage”, “http://www.w3.org/2001/XMLSchema”);
docBuilderFactory.setAttribute(“http://java.sun.com/xml/jaxp/properties/schemaSource”, schemaPath);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlPath);
} catch(DOMException exc) {
exc.printStackTrace();
}
}
[/java]