溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

xml文件如何實(shí)現(xiàn)正確性驗(yàn)證類

發(fā)布時(shí)間:2020-07-13 09:47:13 來(lái)源:億速云 閱讀:180 作者:Leah 欄目:編程語(yǔ)言

xml文件如何實(shí)現(xiàn)正確性驗(yàn)證類?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

 很多時(shí)候我們的應(yīng)用程序或者web程序需要用到xml文件進(jìn)行配置,而最終的程序是需要給客戶使用的,所以xml或者也需要客戶來(lái)寫,而客戶來(lái)寫的話的,就不能保證xml文件絕對(duì)的正確,于是我寫了這個(gè)類,主要功能就是驗(yàn)證xml書寫文件是否符合定義的xsd規(guī)范.

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>

被驗(yàn)證的xml 實(shí)例如下:

<?xml version="1.0" encoding="utf-8" ?>

<Answer>
  <ShortDesc>385</ShortDesc>
  <AnswerValue>1</AnswerValue>
</Answer>

這個(gè)是java版本的類,C# 的類文件如下(是一個(gè)老美寫的,我的類是根據(jù)他的類翻譯過(guò)來(lái)的):

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

看完上述內(nèi)容,你們掌握xml文件如何實(shí)現(xiàn)正確性驗(yàn)證類的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI