闂傚倸鍊搁崐鎼佸磹閹间礁纾瑰瀣捣閻棗銆掑锝呬壕濡ょ姷鍋為悧鐘汇€侀弴銏犖ч柛灞剧煯婢规洖鈹戦缁撶細闁告鍐f瀺鐎广儱娲犻崑鎾舵喆閸曨剛顦繝鈷€鍕垫疁妤犵偛妫濆顕€宕煎顏佹櫊閹鏁愭惔婵堝嚬閻庣懓鎲$换鍕閹烘挻缍囬柕濞垮劤閻熴劌顪冮妶搴′簼缂侇喗鎸搁悾鐑藉础閻愬秶鍠栭幃娆撳箣濠靛洤顦╅梺鎶芥敱閸ㄥ湱妲愰幘瀛樺濠殿喗鍩堟禍婵嬪箞閵娾晛鐐婇柕濞垮€楃粻姘渻閵堝棛澧柣鏃戝墴閻擃剟顢楅崒妤€浜鹃悷娆忓绾炬悂鏌涙惔锝嗘毈鐎殿噮鍋婇獮妯肩磼濡粯顏熼梻浣芥硶閸o箓骞忛敓锟�濠电姷鏁告慨鐑藉极閸涘﹥鍙忛柣鎴f閺嬩線鏌熼梻瀵割槮缁炬儳顭烽弻锝夊箛椤掍焦鍎撶紓浣哄С閸楁娊寮婚悢鍏尖拻閻庨潧澹婂Σ顔剧磽娴e搫啸闁哥姵鐗犲濠氬Ω閳哄倸浜滈梺鍛婄箓鐎氬懘濮€閵堝棛鍘遍梺闈浨归崕閬嶅焵椤掆偓濠€閬嶅箲閵忕姭妲堥柕蹇曞Т閼板灝鈹戦埥鍡楃仴妞ゆ泦鍥棄鐎广儱顦伴埛鎴犵磼鐎n偒鍎ラ柛搴㈠姉缁辨帞鎷犻幓鎺撴婵犵绱曢弫璇茬暦閻旂⒈鏁嶆慨妯夸含閺夋悂姊绘担鍝ユ瀮婵℃ぜ鍔庨幏瀣蓟閵夈儳锛涢梺瑙勫礃椤曆囧礃閳ь剟鎮峰⿰鍐炬█鐎殿喗鎮傚顕€宕奸悢鍝勫汲闂備胶绮ú鏍磹閸︻厸鍋撳鐐
开发学院WEB开发Xml xml文件正确性验证类实现 阅读

xml文件正确性验证类实现

 2010-10-18 09:38:44 来源:WEB开发网 闂傚倸鍊搁崐鎼佸磹閹间礁纾瑰瀣椤愯姤鎱ㄥ鍡楀幊缂傚倹姘ㄩ幉绋款吋閸澀缃曢梻鍌欑濠€閬嶆惞鎼淬劌绐楅柡宥庡亞娑撳秵銇勯弽顐沪闁绘挶鍎甸弻锝夊即閻愭祴鍋撻崷顓涘亾濮樼偓瀚�闂傚倸鍊搁崐鎼佸磹閹间礁纾瑰瀣捣閻棗銆掑锝呬壕濡ょ姷鍋涢ˇ鐢稿极閹剧粯鍋愰柟缁樺笧閳ь剦鍙冨鍝勑ч崶褏浠奸梺璇茬箲閼归箖鎮鹃悜钘夎摕闁靛濡囬崢鐢告⒑鐟欏嫷鍟忛柛鐘崇墵閵嗗倹绺介崨濠勫幈闁硅壈鎻槐鏇熺墡闂備線娼уú銈団偓姘嵆閻涱噣骞掑Δ鈧粻锝嗙節闂堟稑鏆欏ù婊堢畺閺岋綁濮€閳惰泛婀辨竟鏇熺節濮橆厾鍘甸梺缁樺姦閸撴岸鎮樻潏銊ょ箚闁圭粯甯炴晶娑氱磼缂佹ḿ娲寸€规洖宕灃闁告劕鍟犻崜婵堟崲濞戞ḿ鏆嗗┑鐘辫兌閺佹牜绱撴担浠嬪摵闁圭懓娲ら悾鐑藉箳閹搭厽鍍甸梺鐟板悁閻掞箓鎮楅幖浣光拻濞达絿鍎ら崵鈧梺鎼炲€栭悧鐘荤嵁韫囨稒鏅搁柨鐕傛嫹婵犵數濮烽弫鍛婃叏閻戣棄鏋侀柛娑橈攻閸欏繑銇勯幘鍗炵仼缂佺媭鍨堕弻娑㈠箛闂堟稒鐏堥悗鐟版啞缁诲啴濡甸崟顖氱閻庨潧鎽滈悾濂告⒑绾拋娼愭繛鑼枎椤繒绱掑Ο鑲╂嚌闂侀€炲苯澧畝锝堝劵椤︽煡鎮¢妶澶嬬厪闁割偅绻冮崑顏呯箾瀹割喕绨婚幆鐔兼⒑鐎圭姵銆冮柤鍐茬埣瀹曟繈鏁冮埀顒勨€旈崘顔嘉ч柛鈩冾殘閻熸劙姊洪悡搴℃毐闁绘牕銈稿畷鐑樼節閸パ冨祮闂侀潧楠忕槐鏇㈠储椤忓牊鈷戦柟鑲╁仜閸旀鏌¢崨顔锯姇缂佸倹甯熼ˇ瀵哥磼鏉堛劌绗氭繛鐓庣箻閸┾剝鎷呴柨瀣垫綗闂傚倷娴囧銊╂倿閿曞倸绠查柛銉墮閺嬩線鏌熼崜褏甯涢柡鍛倐閺屻劑鎮ら崒娑橆伓闂傚倸鍊搁崐鎼佸磹閹间礁纾瑰瀣椤愯姤鎱ㄥ鍡楀幊缂傚倹姘ㄩ幉绋款吋閸澀缃曢梻鍌欑濠€閬嶆惞鎼淬劌绐楅柡宥庡亞娑撳秵銇勯弽顐沪闁绘挶鍎甸弻锝夊即閻愭祴鍋撻崷顓涘亾濮樼偓瀚�  闂傚倸鍊搁崐鎼佸磹閹间礁纾归柣鎴eГ閸ゅ嫰鏌ら崫銉︽毄濞寸姵姘ㄧ槐鎾诲磼濞嗘帒鍘$紓渚囧櫘閸ㄥ爼濡撮崘顔煎窛闁哄鍨归崢娲倵楠炲灝鍔氭い锔诲灦瀹曪繝骞庨懞銉у帾闂婎偄娲﹀ú鏍ㄧ墡闂備浇顕х€垫帡宕滈悢濂夋綎闁惧繐婀辩壕鍏间繆椤栨碍鎯堟い顐㈢Т椤啴濡堕崱妤€顫庨梺鍛婎焼閸パ呭弨婵犮垼娉涜癌闁绘柨鍚嬮悡銉╂倵閿濆骸鍘撮柛瀣尰缁绘繂顫濋娑欏闁荤喐绮庢晶妤冩暜閹烘挾顩插ù鐓庣摠閻撴洟鏌熼幆褜鍤熼柍钘夘樀閺屽秶绱掑Ο鑽ゅ弳濡炪値鍋呯换鍫ュ箠濠婂懎鏋堟俊顖濐嚙椤忓綊姊婚崒娆戭槮闁硅绱曠划娆撳箣閿斿搫浜奸梺鍝勵槹閸ㄧ喖寮搁弮鍫熺厸闁告劧绲芥禍鍓х磽娴h櫣甯涚紒瀣尰缁傛帡鏁冮崒姘憋紲濠殿喗锕╅崜锕傛倵閹惰姤鈷掑ù锝呮憸閿涘秶绱掗鍛仸妤犵偞鍨垮畷鍫曨敆閸屾氨銈﹂梺璇插嚱缂嶅棙绂嶉弽顓炵哗濞寸姴顑嗛悡娆撴⒑椤撱劎鐣卞褜鍨遍妵鍕棘閸喒鍋撶憴鍕攳濠电姴娲﹂崐閿嬨亜韫囨挸顏ら柛瀣崌瀵€燁檨婵炲吋鐗曢埞鎴︽偐鐎圭姴顥濋梺绋胯閸斿酣骞夊宀€鐤€婵炴垶岣块悿鍛存⒑閸︻叀妾搁柛鐘愁殜瀵煡骞栨担鍦弳闂佺粯娲栭崐鍦偓姘炬嫹
核心提示:很多时候我们的应用程序或者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;
    }
  }
}
 
 

类的使用方法如下:

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

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

Tags:xml 文件 正确性

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接