xml文件正确性验证类实现
2010-10-18 09:38:44 来源:WEB开发网核心提示:很多时候我们的应用程序或者web程序需要用到xml文件进行配置,而最终的程序是需要给客户使用的,所以xml或者也需要客户来写,而客户来写的话的,就不能保证xml文件绝对的正确,于是我写了这个类,主要功能就是验证xml书写文件是否符合定义的xsd规范.package common.xml.validator;import
很多时候我们的应用程序或者web程序需要用到xml文件进行配置,而最终的程序是需要给客户使用的,所以xml或者也需要客户来写,而客户来写的话的,就不能保证xml文件绝对的正确,于是我写了这个类,主要功能就是验证xml书写文件是否符合定义的xsd规范.
package common.xml.validator;import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.net.URL;import javax.xml.XMLConstants; 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.xml.sax.SAXException;/** *//** * @author suyuan * */ public class XmlSchemaValidator { private boolean isValid = true; private String xmlErr = ""; public boolean isValid() { return isValid; } public String getXmlErr() { return xmlErr; } public XmlSchemaValidator() { } public boolean ValidXmlDoc(String xml,URL schema) { StringReader reader = new StringReader(xml); return ValidXmlDoc(reader,schema); } public boolean ValidXmlDoc(Reader xml,URL schema) { try { InputStream schemaStream = schema.openStream(); Source xmlSource = new StreamSource(xml); Source schemaSource = new StreamSource(schemaStream); return ValidXmlDoc(xmlSource,schemaSource); } catch (IOException e) { isValid = false; xmlErr = e.getMessage(); return false; } } public boolean ValidXmlDoc(String xml,File schema) { StringReader reader = new StringReader(xml); return ValidXmlDoc(reader,schema); } public boolean ValidXmlDoc(Reader xml,File schema) { try { FileInputStream schemaStream = new FileInputStream(schema); Source xmlSource = new StreamSource(xml); Source schemaSource = new StreamSource(schemaStream); return ValidXmlDoc(xmlSource,schemaSource); } catch (IOException e) { isValid = false; xmlErr = e.getMessage(); return false; } } public boolean ValidXmlDoc(Source xml,Source schemaSource) { try { SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if(xml==null||xml.equals("")) { return false; } Schema schema = schemafactory.newSchema(schemaSource); Validator valid = schema.newValidator(); valid.validate(xml); return true; } catch (SAXException e) { isValid = false; xmlErr = e.getMessage(); return false; } catch (IOException e) { isValid = false; xmlErr = e.getMessage(); return false; } catch (Exception e) { isValid = false; xmlErr = e.getMessage(); return false; } } }
更多精彩
赞助商链接