利用Schema验证xml的代码
2008-08-26 10:39
363 查看
首先建立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
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
相关文章推荐
- 如何用schema验证xml(MSXML),简单VC代码
- 利用ASP发送和接收XML数据的处理方法与代码
- XML之Schema验证
- [代码]使用XSD验证XML示例(LINQ to XML)(转)
- 利用代码读取XML文档
- 使用schema验证xml文档的合法性
- php利用正则表达式实现手机号码格式验证代码
- 关于利用Schema解析XML,生成、编辑XML的节点问题
- xml基础、DTD验证、Schema验证(备忘)
- 在Delphi中用Schema验证XML
- 利用XML缓存数据达到缓解数据库服务器压力的代码利用片段
- Java程序员从笨鸟到菜鸟之(二十五)XML之Schema验证
- 关于利用cmarkup类将xml转成树的递归代码
- C#中用schema验证xml的合法性
- Delphi 7验证XML合法性(利用DTD、XSD)
- C#中用schema验证xml的合法性
- 单点登录(十一)-----遇到问题-----cas启用mongodb验证方式报错--Unable to locate Spring NamespaceHandler for XML schema na
- Java程序员从笨鸟到菜鸟之(二十五)XML之Schema验证
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式