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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

XML檔可以用PPT開啟嗎? XML,即可擴展標記語言(ExtensibleMarkupLanguage),是一種廣泛應用於資料交換和資料儲存的通用標記語言。與HTML相比,XML更加靈活,能夠定義自己的標籤和資料結構,使得資料的儲存和交換更加方便和統一。而PPT,即PowerPoint,是微軟公司開發的一種用於創建簡報的軟體。它提供了圖文並茂的方

使用Python實現XML資料的合併和去重XML(eXtensibleMarkupLanguage)是一種用於儲存和傳輸資料的標記語言。在處理XML資料時,有時候我們需要將多個XML檔案合併成一個,或移除重複的資料。本文將介紹如何使用Python實現XML資料的合併和去重的方法,並給出對應的程式碼範例。一、XML資料合併當我們有多個XML文件,需要將其合

Python中的XML資料轉換為CSV格式XML(ExtensibleMarkupLanguage)是一種可擴充標記語言,常用於資料的儲存與傳輸。而CSV(CommaSeparatedValues)則是一種以逗號分隔的文字檔案格式,常用於資料的匯入和匯出。在處理資料時,有時需要將XML資料轉換為CSV格式以便於分析和處理。 Python作為一種功能強大

使用Python實現XML資料的篩選和排序引言:XML是一種常用的資料交換格式,它以標籤和屬性的形式儲存資料。在處理XML資料時,我們經常需要對資料進行篩選和排序。 Python提供了許多有用的工具和函式庫來處理XML數據,本文將介紹如何使用Python實現XML資料的篩選和排序。讀取XML檔案在開始之前,我們需要先讀取XML檔案。 Python有許多XML處理函式庫,

Python實作XML與JSON之間的轉換導語:在日常的開發過程中,我們常常需要將資料在不同的格式之間轉換。 XML和JSON是常見的資料交換格式,在Python中,我們可以使用各種函式庫來實作XML和JSON之間的相互轉換。本文將介紹幾種常用的方法,並附帶程式碼範例。一、XML轉JSON在Python中,我們可以使用xml.etree.ElementTree模

使用Python處理XML中的錯誤和異常XML是一種常用的資料格式,用於儲存和表示結構化的資料。當我們使用Python處理XML時,有時可能會遇到一些錯誤和異常。在本篇文章中,我將介紹如何使用Python來處理XML中的錯誤和異常,並提供一些範例程式碼供參考。使用try-except語句捕捉XML解析錯誤當我們使用Python解析XML時,有時候可能會遇到一些

Python解析XML中的特殊字元和轉義序列XML(eXtensibleMarkupLanguage)是一種常用的資料交換格式,用於在不同系統之間傳輸和儲存資料。在處理XML檔案時,經常會遇到包含特殊字元和轉義序列的情況,這可能會導致解析錯誤或誤解資料。因此,在使用Python解析XML檔案時,我們需要了解如何處理這些特殊字元和轉義序列。一、特殊字元和

C#開發中如何處理XML和JSON資料格式,需要具體程式碼範例在現代軟體開發中,XML和JSON是廣泛應用的兩種資料格式。 XML(可擴展標記語言)是一種用於儲存和傳輸資料的標記語言,而JSON(JavaScript物件表示)是一種輕量級的資料交換格式。在C#開發中,我們經常需要處理和操作XML和JSON數據,本文將重點放在如何使用C#處理這兩種數據格式,並附上
