xml文件如何实现正确性验证类

xml文件如何实现正确性验证类?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

兴隆台网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、自适应网站建设等网站项目制作,到程序开发,运营维护。创新互联公司于2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

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

类的使用方法如下:

package common.xml.validator;

import java.io.*;
import java.net.URL;

public class testXmlValidator {

  /** *//**
   * @param args
   */
  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文件如何实现正确性验证类的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网站题目:xml文件如何实现正确性验证类
分享URL:http://ybzwz.com/article/gjohhh.html