栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > 其他 > xml语言

xml文件正确性验证类的示例代码分析

xml语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

xml文件正确性验证类的示例代码分析

很多时候我们的应用程序或者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;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;    }  }}

类的使用方法如下:

package common.xml.validator;import java.io.*;import java.net.URL;public class testXmlValidator {    public static void main(String[] args) {    InputStream XmlStream = testXmlValidator.class.getResourceAsStream("test.xml");    Reader XmlReader = new InputStreamReader(XmlStream);    URL schema =testXmlValidator.class.getResource("valid.xsd");    XmlSchemaValidator xmlvalid = new XmlSchemaValidator();    System.out.println(xmlvalid.ValidXmlDoc(XmlReader, schema));    System.out.print(xmlvalid.getXmlErr());  }}

xsd文件定义如下:

                                

被验证的xml 实例如下:

  385  1

这个是java版本的类,C# 的类文件如下(是一个老美写的,我的类是根据他的类翻译过来的):

using System;using System.Xml;using System.Xml.Schema;using System.IO;namespace ProtocolManager.WebApp{  ///   /// This class validates an xml string or xml document against an xml schema.  /// It has public methods that return a boolean value depending on the validation  /// of the xml.  ///   public class XmlSchemaValidator  {    private bool isValidXml = true;    private string validationError = "";    ///     /// Empty Constructor.    ///     public XmlSchemaValidator()    {    }    ///     /// Public get/set access to the validation error.    ///     public String ValidationError    {      get      {        return "" + this.validationError + "";      }      set      {        this.validationError = value;      }    }    ///     /// Public get access to the isValidXml attribute.    ///     public bool IsValidXml    {      get      {        return this.isValidXml;      }    }    ///     /// This method is invoked when the XML does not match    /// the XML Schema.    ///     ///     ///     private void ValidationCallBack(object sender, ValidationEventArgs args)    {      // The xml does not match the schema.      isValidXml = false;      this.ValidationError = args.Message;    }     ///     /// This method validates an xml string against an xml schema.    ///     /// XML string    /// XML Schema Namespace    /// XML Schema Uri    /// bool    public bool ValidXmlDoc(string xml, string schemaNamespace, string schemaUri)    {      try      {        // Is the xml string valid?        if(xml == null || xml.Length < 1)        {          return false;        }        StringReader srXml = new StringReader(xml);        return ValidXmlDoc(srXml, schemaNamespace, schemaUri);      }      catch(Exception ex)      {        this.ValidationError = ex.Message;        return false;      }    }    ///     /// This method validates an xml document against an xml schema.    ///     /// Xmldocument    /// XML Schema Namespace    /// XML Schema Uri    /// bool    public bool ValidXmlDoc(Xmldocument xml, string schemaNamespace, string schemaUri)    {      try      {        // Is the xml object valid?        if(xml == null)        {          return false;        }        // Create a new string writer.        StringWriter sw = new StringWriter();        // Set the string writer as the text writer to write to.        XmlTextWriter xw = new XmlTextWriter(sw);        // Write to the text writer.        xml.WriteTo(xw);        // Get        string strXml = sw.ToString();        StringReader srXml = new StringReader(strXml);        return ValidXmlDoc(srXml, schemaNamespace, schemaUri);      }      catch(Exception ex)      {        this.ValidationError = ex.Message;        return false;      }    }    ///     /// This method validates an xml string against an xml schema.    ///     /// StringReader containing xml    /// XML Schema Namespace    /// XML Schema Uri    /// bool    public bool ValidXmlDoc(StringReader xml, string schemaNamespace, string schemaUri)    {      // Continue?      if(xml == null || schemaNamespace == null || schemaUri == null)      {        return false;      }      isValidXml = true;      XmlValidatingReader vr;      XmlTextReader tr;      XmlSchemaCollection schemaCol = new XmlSchemaCollection();      schemaCol.Add(schemaNamespace, schemaUri);      try      {        // Read the xml.        tr = new XmlTextReader(xml);        // Create the validator.        vr = new XmlValidatingReader(tr);        // Set the validation tyep.        vr.ValidationType = ValidationType.Auto;        // Add the schema.        if(schemaCol != null)        {          vr.Schemas.Add(schemaCol);        }        // Set the validation event handler.        vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);        // Read the xml schema.        while(vr.Read())        {        }        vr.Close();        return isValidXml;      }      catch(Exception ex)      {        this.ValidationError = ex.Message;        return false;      }      finally      {        // Clean up        vr = null;        tr = null;      }    }  }}

希望 以上类对大家有所帮助,当然我也是在这里做一个标记,以后有需要可以直接用了 呵呵

以上就是xml文件正确性验证类的示例代码分析的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/794511.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号