WEB开发网
开发学院WEB开发Xml xml文件正确性验证类实现 阅读

xml文件正确性验证类实现

 2010-10-18 09:38:44 来源:WEB开发网   
核心提示:类的使用方法如下:package common.xml.validator;import java.io.*;import java.net.URL;public class testXmlValidator {/** *//** * @param args */public static void main(Stri

类的使用方法如下:

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;
      }
    }
  }
}

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

上一页  1 2 

Tags:xml 文件 正确性

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接