搜尋
首頁後端開發XML/RSS教程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檔案正確性驗證類別的範例程式碼分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
從XML到可讀的內容:揭開RSS feed的神秘面紗從XML到可讀的內容:揭開RSS feed的神秘面紗Apr 11, 2025 am 12:03 AM

rssfeedsarexmldocuments usedforcontentAggregation and distribution.totransformthemintoreadableContent:1)parsethethexmlusinglibrarieslibrariesliblarieslikeparserinparserinpython.2)andledifferentifferentrssssssssssssssssssssssssssssssssssssssssssssssersions andpotentionparsingrorS.3)

是否有基於JSON的RSS替代方案?是否有基於JSON的RSS替代方案?Apr 10, 2025 am 09:31 AM

JSONFeed是一種基於JSON的RSS替代方案,其優勢在於簡潔性和易用性。 1)JSONFeed使用JSON格式,易於生成和解析。 2)它支持動態生成,適用於現代Web開發。 3)使用JSONFeed可以提升內容管理效率和用戶體驗。

RSS文檔工具:構建,驗證和發布提要RSS文檔工具:構建,驗證和發布提要Apr 09, 2025 am 12:10 AM

如何構建、驗證和發布RSSfeeds? 1.構建:使用Python腳本生成RSSfeed,包含標題、鏈接、描述和發布日期。 2.驗證:使用FeedValidator.org或Python腳本檢查RSSfeed是否符合RSS2.0標準。 3.發布:將RSS文件上傳到服務器,或使用Flask動態生成並發布RSSfeed。通過這些步驟,你可以有效管理和分享內容。

確保您的XML/RSS提要:全面的安全清單確保您的XML/RSS提要:全面的安全清單Apr 08, 2025 am 12:06 AM

確保XML/RSSfeeds安全性的方法包括:1.數據驗證,2.加密傳輸,3.訪問控制,4.日誌和監控。這些措施通過網絡安全協議、數據加密算法和訪問控制機制來保護數據的完整性和機密性。

XML/RSS面試問題和答案:提高您的專業知識XML/RSS面試問題和答案:提高您的專業知識Apr 07, 2025 am 12:19 AM

XML是一種標記語言,用於存儲和傳輸數據,RSS是一種基於XML的格式,用於發布頻繁更新的內容。 1)XML通過標籤和屬性描述數據結構,2)RSS定義特定標籤發布和訂閱內容,3)使用Python的xml.etree.ElementTree模塊可以創建和解析XML,4)XPath表達式可查詢XML節點,5)feedparser庫可解析RSSfeed,6)常見錯誤包括標籤不匹配和編碼問題,可用xmllint驗證,7)使用SAX解析器處理大型XML文件可優化性能。

高級XML/RSS教程:ACE您的下一次技術採訪高級XML/RSS教程:ACE您的下一次技術採訪Apr 06, 2025 am 12:12 AM

XML是一種用於數據存儲和交換的標記語言,RSS是基於XML的格式,用於發布更新內容。 1.XML定義數據結構,適合數據交換和存儲。 2.RSS用於內容訂閱,解析時使用專門庫。 3.解析XML可使用DOM或SAX,生成XML和RSS需正確設置元素和屬性。

從XML/RSS到JSON:現代數據轉換策略從XML/RSS到JSON:現代數據轉換策略Apr 05, 2025 am 12:08 AM

使用Python可以從XML/RSS轉換到JSON。 1)解析源數據,2)提取字段,3)轉換為JSON,4)輸出JSON。使用xml.etree.ElementTree和feedparser庫解析XML/RSS,使用json庫生成JSON數據。

XML/RSS和REST API:現代網絡開發的最佳實踐XML/RSS和REST API:現代網絡開發的最佳實踐Apr 04, 2025 am 12:08 AM

XML/RSS和RESTAPI在現代網絡開發中協同工作,通過以下方式:1)XML/RSS用於內容髮布和訂閱,2)RESTAPI用於設計和操作網絡服務。結合使用這兩者可以實現高效的內容管理和動態更新。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境