利用Schema验证xml的代码

首先建立handler用来保存验证过程中发现的出错信息

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import org.xml.sax.ErrorHandler;
  4. import org.xml.sax.SAXException;
  5. import org.xml.sax.SAXParseException;
  6. /**
  7.  * @author Haiyan Wang
  8.  * @version 1 Oct 26, 2007
  9.  */
  10. public class XmlParserErrorHander implements ErrorHandler {
  11.     private List<String>errors;
  12.     private int index = 1;
  13.     
  14.     /**
  15.      * return errors
  16.      *
  17.      */
  18.     public List<String> getErrors( ) {
  19.         return errors;
  20.     }
  21.     /**
  22.      * @param errors 
  23.      *        the errors to set
  24.      */
  25.     public void setErrors(List<String> errors) {
  26.         this.errors = errors;
  27.     }
  28.     /**
  29.      * 
  30.      */
  31.     public XmlParserErrorHander(){
  32.         errors = new ArrayList<String>();
  33.     }
  34.     
  35.     /* (non-Javadoc)
  36.      * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
  37.      */
  38.     public void error(SAXParseException exception) throws SAXException {
  39.         errors.add(exception.getMessage());
  40.     }
  41.     
  42.     /* (non-Javadoc)
  43.      * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
  44.      */
  45.     public void fatalError(SAXParseException exception) throws SAXException {
  46.         errors.add(exception.getMessage());
  47.     }
  48.     
  49.     /* (non-Javadoc)
  50.      * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
  51.      */
  52.     public void warning(SAXParseException exception) throws SAXException {
  53.         errors.add(exception.getMessage());
  54.     }
  55.     
  56.     public void addError(String error){
  57.         errors.add(error);
  58.     }
  59.     
  60.     public boolean hasError(){
  61.         return (errors != null) && (errors.size() > 0);
  62.     }
  63. }

Parse xml的方法-这个方法的作用就是将传入的xml文件解析成Dodument对象,在解析的过程中利用Schema对xml进行验证,如果xml有错,则错误会被保存在Handler中:

  1. /**
  2.      * @param schemaContent
  3.      * @param xmlContent
  4.      * @return
  5.      * @throws Exception
  6.      */
  7.     public static Document getDocmentNode(String xmlContent, String schemaContent)
  8.             throws Exception {
  9.         if(logger.isDebugEnabled()){
  10.             logger.debug("  Enter getDocmentNode(String xmlContent, String schemaContent)");
  11.         } 
  12.         
  13.         InputStream is = new ByteArrayInputStream(xmlContent.getBytes());
  14.         InputStream schemaIs = new ByteArrayInputStream(schemaContent.getBytes());
  15.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  16.         Document doc = null;
  17.         XmlParserErrorHander hander = new XmlParserErrorHander();
  18.         try {
  19.              SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  20.              Source schemaSource = new StreamSource(schemaIs);
  21.               Schema schema = schemaFactory.newSchema(schemaSource); 
  22.               javax.xml.validation.Validator validator = schema.newValidator(); 
  23.               Source source = new StreamSource(is);
  24.               validator.setErrorHandler(hander);
  25.               validator.validate(source);
  26.     
  27.             factory.setIgnoringComments(true);
  28.             factory.setIgnoringElementContentWhitespace(true);
  29.             // As I tested before, if uses validator, the is would be changed,
  30.             // so I have to create a new InputStream.
  31.             ByteArrayInputStream is2 =
  32.                 new ByteArrayInputStream(xmlContent.getBytes());
  33.             DocumentBuilder builder = factory.newDocumentBuilder();
  34.             doc = builder.parse(is2);
  35.             doc.normalize();
  36.         } catch (ParserConfigurationException e) {
  37.             hander.getErrors().add(e.getMessage());
  38.             logger.error(e.getMessage(), e);
  39.         } catch (FileNotFoundException e) {
  40.             hander.getErrors().add(e.getMessage());
  41.             logger.error(e.getMessage(), e);
  42.         } catch (SAXException e) {
  43.             hander.getErrors().add(e.getMessage());
  44.             logger.error(e.getMessage(), e);
  45.         } catch (IOException e) {
  46.             hander.getErrors().add(e.getMessage());
  47.             logger.error(e.getMessage(), e);
  48.         }
  49.         
  50.         if (hander.getErrors().size() > 0) {
  51.             logger.error("Met " + hander.getErrors().size() + " when parsed the xml.");
  52.             StringBuffer buffer =
  53.                 new StringBuffer("");
  54.             
  55.             for (String error : hander.getErrors()) {
  56.                 buffer.append(error).append(Constants.ERROR_MESSAGE_SPLIT);
  57.             }
  58.             buffer.delete(buffer.lastIndexOf(Constants.ERROR_MESSAGE_SPLIT), buffer.length());
  59.             logger.error("Error met when get the document from the xml: " + buffer.toString());
  60.             throw new Exception(buffer.toString());
  61.         }
  62.         
  63.         if(logger.isDebugEnabled()){
  64.             logger.debug("      Exit getDocmentNode(String xmlContent, String schemaContent)");
  65.         }
  66.         return doc;
  67.     }

关于xml的验证,可以参阅:

http://blog.csdn.net/haydenwang8287/archive/2007/09/13/1784398.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值