DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> XML學習教程 >> XML詳解 >> xml 文件正確性驗證類實現
xml 文件正確性驗證類實現
編輯: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;
  
/** *//**
* @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文件定義如下:

<xs:schema id="XSDSchemaTest"
 XMLns:xs="http://www.w3.org/2001/XMLSchema"
 elementFormDefault="qualifIEd"
 attributeFormDefault="unqualifIEd"
>
  
<xs:simpleType name="FamilyMemberType">
 <xs:restriction base="xs:string">
  <xs:enumeration value="384" />
  <xs:enumeration value="385" />
  <xs:enumeration value="386" />
  <xs:enumeration value="" />
 </xs:restriction>    
</xs:simpleType>
  
  <xs:element name="Answer">
   <xs:complexType>
  <xs:sequence>
   <xs:element name="ShortDesc" type="FamilyMemberType" />
   <xs:element name="AnswerValue" type="xs:int" />
   </xs:sequence>
   </xs:complexType>
   </xs:element>
  
</xs:schema>

被驗證的XML 實例如下:

<?XML version="1.0" encoding="utf-8" ?>
  
<Answer>
  <ShortDesc>385</ShortDesc>
  <AnswerValue>1</AnswerValue>
</Answer>

  這個是Java版本的類,C# 的類文件如下(是一個老美寫的,我的類是根據他的類翻譯過來的):

using System;
using System.XML;
using System.XML.Schema;
using System.IO;
  
namespace ProtocolManager.WebApp
{
  /**//// <summary>
  /// 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.
  /// </summary>
  public class XMLSchemaValidator
  {
    private bool isValidXML = true;
    private string validationError = "";
  
    /**//// <summary>
    /// Empty Constructor.
    /// </summary>
    public XMLSchemaValidator()
    {
      
    }
  
    /**//// <summary>
    /// Public get/set Access to the validation error.
    /// </summary>
    public String ValidationError
    {
      get
      {
        return "<ValidationError>" + this.validationError + "</ValidationError>";
      }
      set
      {
        this.validationError = value;
      }
    }
  
    /**//// <summary>
    /// Public get Access to the isValidXML attribute.
    /// </summary>
    public bool IsValidXML
    {
      get
      {
        return this.isValidXML;
      }
    }
  
    /**//// <summary>
    /// This method is invoked when the XML does not match
    /// the XML Schema.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    private void ValidationCallBack(object sender, ValidationEventArgs args)
    {
      // The XML does not match the schema.
      isValidXML = false;
      this.ValidationError = args.Message;
    } 
  
    /**//// <summary>
    /// This method validates an xml string against an XML schema.
    /// </summary>
    /// <param name="xml">XML string</param>
    /// <param name="schemaNamespace">XML Schema Namespace</param>
    /// <param name="schemaUri">XML Schema Uri</param>
    /// <returns>bool</returns>
    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;
      }
    }
  
    /**//// <summary>
    /// This method validates an xml document against an XML schema.
    /// </summary>
    /// <param name="xml">XMLDocument</param>
    /// <param name="schemaNamespace">XML Schema Namespace</param>
    /// <param name="schemaUri">XML Schema Uri</param>
    /// <returns>bool</returns>
    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;
      }
    }
  
    /**//// <summary>
    /// This method validates an xml string against an XML schema.
    /// </summary>
    /// <param name="xml">StringReader containing XML</param>
    /// <param name="schemaNamespace">XML Schema Namespace</param>
    /// <param name="schemaUri">XML Schema Uri</param>
    /// <returns>bool</returns>
    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學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved