首先建立handler用来保存验证过程中发现的出错信息
- import java.util.ArrayList;
- import java.util.List;
- import org.xml.sax.ErrorHandler;
- import org.xml.sax.SAXException;
- import org.xml.sax.SAXParseException;
- /**
- * @author Haiyan Wang
- * @version 1 Oct 26, 2007
- */
- public class XmlParserErrorHander implements ErrorHandler {
- private List<String>errors;
- private int index = 1;
- /**
- * return errors
- *
- */
- public List<String> getErrors( ) {
- return errors;
- }
- /**
- * @param errors
- * the errors to set
- */
- public void setErrors(List<String> errors) {
- this.errors = errors;
- }
- /**
- *
- */
- public XmlParserErrorHander(){
- errors = new ArrayList<String>();
- }
- /* (non-Javadoc)
- * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
- */
- public void error(SAXParseException exception) throws SAXException {
- errors.add(exception.getMessage());
- }
- /* (non-Javadoc)
- * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
- */
- public void fatalError(SAXParseException exception) throws SAXException {
- errors.add(exception.getMessage());
- }
- /* (non-Javadoc)
- * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
- */
- public void warning(SAXParseException exception) throws SAXException {
- errors.add(exception.getMessage());
- }
- public void addError(String error){
- errors.add(error);
- }
- public boolean hasError(){
- return (errors != null) && (errors.size() > 0);
- }
- }
Parse xml的方法-这个方法的作用就是将传入的xml文件解析成Dodument对象,在解析的过程中利用Schema对xml进行验证,如果xml有错,则错误会被保存在Handler中:
- /**
- * @param schemaContent
- * @param xmlContent
- * @return
- * @throws Exception
- */
- public static Document getDocmentNode(String xmlContent, String schemaContent)
- throws Exception {
- if(logger.isDebugEnabled()){
- logger.debug(" Enter getDocmentNode(String xmlContent, String schemaContent)");
- }
- InputStream is = new ByteArrayInputStream(xmlContent.getBytes());
- InputStream schemaIs = new ByteArrayInputStream(schemaContent.getBytes());
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- Document doc = null;
- XmlParserErrorHander hander = new XmlParserErrorHander();
- try {
- SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
- Source schemaSource = new StreamSource(schemaIs);
- Schema schema = schemaFactory.newSchema(schemaSource);
- javax.xml.validation.Validator validator = schema.newValidator();
- Source source = new StreamSource(is);
- validator.setErrorHandler(hander);
- validator.validate(source);
- factory.setIgnoringComments(true);
- factory.setIgnoringElementContentWhitespace(true);
- // As I tested before, if uses validator, the is would be changed,
- // so I have to create a new InputStream.
- ByteArrayInputStream is2 =
- new ByteArrayInputStream(xmlContent.getBytes());
- DocumentBuilder builder = factory.newDocumentBuilder();
- doc = builder.parse(is2);
- doc.normalize();
- } catch (ParserConfigurationException e) {
- hander.getErrors().add(e.getMessage());
- logger.error(e.getMessage(), e);
- } catch (FileNotFoundException e) {
- hander.getErrors().add(e.getMessage());
- logger.error(e.getMessage(), e);
- } catch (SAXException e) {
- hander.getErrors().add(e.getMessage());
- logger.error(e.getMessage(), e);
- } catch (IOException e) {
- hander.getErrors().add(e.getMessage());
- logger.error(e.getMessage(), e);
- }
- if (hander.getErrors().size() > 0) {
- logger.error("Met " + hander.getErrors().size() + " when parsed the xml.");
- StringBuffer buffer =
- new StringBuffer("");
- for (String error : hander.getErrors()) {
- buffer.append(error).append(Constants.ERROR_MESSAGE_SPLIT);
- }
- buffer.delete(buffer.lastIndexOf(Constants.ERROR_MESSAGE_SPLIT), buffer.length());
- logger.error("Error met when get the document from the xml: " + buffer.toString());
- throw new Exception(buffer.toString());
- }
- if(logger.isDebugEnabled()){
- logger.debug(" Exit getDocmentNode(String xmlContent, String schemaContent)");
- }
- return doc;
- }
关于xml的验证,可以参阅:
http://blog.csdn.net/haydenwang8287/archive/2007/09/13/1784398.aspx