1. Introduction
First, I decided to write this article to share some of intuited knowledge, try to help and demonstrate how it is possible to develop a simple and generic module for validating XML files with their respective schema files.
2. Project Structure
3. XmlAndSchemaValidator Class Library Source Code
- using System;
- using System.Xml;
- using System.Xml.Schema;
- using System.IO;
- using System.Text;
-
- namespace XmlAndSchemaValidator
- {
- public class Validator
- {
- #region Attributes
- private System.Xml.XmlTextReader _XmlTextReader = null;
- private System.Xml.XmlReader _XmlReader = null;
- private System.Xml.XmlReaderSettings _XmlReaderSettings = null;
- private System.Xml.XmlParserContext _XmlParserContext = null;
- private System.Xml.Schema.XmlSchemaSet _XmlSchemaSet = null;
- private string _ValidationError = string.Empty;
- #endregion
-
- #region Object Constructor
- public Validator()
- {
- this._XmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();
- this._XmlParserContext = new System.Xml.XmlParserContext(null, null, "", XmlSpace.None);
-
- ValidationEventHandler _ValidationEventHandler = new ValidationEventHandler(ValidationErrors);
- }
- #endregion
-
- #region Validate
-
- public string Validate(Int32 _EncodingType, FileInfo _XmlFile, XmlNodeType _XmlNodeType, string _Namespace, string _URI)
- {
- System.Text.UTF8Encoding _UTF8Encoding = new System.Text.UTF8Encoding();
- System.Text.UTF32Encoding _UTF32Encoding = new System.Text.UTF32Encoding();
- System.Text.Encoding _Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
- Int32 _StartIndex = 0;
- Int32 _EndIndex = 0;
- string _XmlString = string.Empty;
- Byte[] _Buffer = null;
- FileStream _FileStream = null;
-
- try
- {
-
- if (_XmlFile.Exists)
- {
- try
- {
- _FileStream = _XmlFile.OpenRead();
- _Buffer = new Byte[_FileStream.Length];
-
- _FileStream.Read(_Buffer, 0, _Buffer.Length);
-
-
- switch (_EncodingType.ToString())
- {
- case "1":
- _XmlString = _UTF8Encoding.GetString(_Buffer);
- break;
-
- case "2":
- _XmlString = _UTF32Encoding.GetString(_Buffer);
- break;
-
- case "3":
- _XmlString = _Encoding.GetString(_Buffer);
- break;
- }
-
- _XmlString = _XmlString.Replace("\r", "");
- _XmlString = _XmlString.Replace("\n", "");
- _XmlString = _XmlString.Replace("\t", "");
-
- _FileStream.Close();
- }
- catch
- {
- _FileStream.Close();
- }
- }
-
-
- this._XmlSchemaSet.Add(_Namespace, _URI);
-
-
- this._XmlTextReader = new XmlTextReader(_XmlString, _XmlNodeType, this._XmlParserContext);
- this._XmlTextReader.Read();
-
-
- this._XmlReaderSettings = new System.Xml.XmlReaderSettings();
- this._XmlReaderSettings.ValidationType = ValidationType.Schema;
- this._XmlReaderSettings.IgnoreComments = true;
- this._XmlReaderSettings.IgnoreWhitespace = true;
-
-
- this._XmlReaderSettings.Schemas.Add(_Namespace, _URI);
-
-
- this._XmlReaderSettings.ConformanceLevel = ConformanceLevel.Auto;
-
-
- this._XmlReader = System.Xml.XmlReader.Create(this._XmlTextReader, this._XmlReaderSettings);
-
-
-
- while (this._XmlReader.Read())
- {
-
- }
- }
- catch (XmlException _XmlException)
- {
- this._ValidationError = _XmlException.Message;
- }
- catch (XmlSchemaException _XmlSchemaException)
- {
- this._ValidationError = _XmlSchemaException.Message;
- }
- catch (Exception _Exception)
- {
- this._ValidationError = _Exception.Message;
- }
-
-
- if (this._ValidationError.Trim().ToString() != string.Empty)
- {
- _StartIndex = this._ValidationError.IndexOf("An error occurred at");
- _EndIndex = this._ValidationError.Length - (this._ValidationError.Length - _StartIndex);
-
- if (_StartIndex >= 0)
- this._ValidationError = this._ValidationError.Substring(0, _EndIndex);
- }
-
- return this._ValidationError;
- }
-
-
- public string Validate(string _XmlString, XmlNodeType _XmlNodeType, string _Namespace, string _URI)
- {
- Int32 _StartIndex = 0;
- Int32 _EndIndex = 0;
-
- try
- {
-
- this._XmlSchemaSet.Add(_Namespace, _URI);
-
-
- this._XmlTextReader = new XmlTextReader(_XmlString, _XmlNodeType, this._XmlParserContext);
- this._XmlTextReader.Read();
-
-
- this._XmlReaderSettings = new System.Xml.XmlReaderSettings();
- this._XmlReaderSettings.ValidationType = ValidationType.Schema;
- this._XmlReaderSettings.IgnoreComments = true;
- this._XmlReaderSettings.IgnoreWhitespace = true;
-
-
- this._XmlReaderSettings.Schemas.Add(_Namespace, _URI);
-
-
- this._XmlReaderSettings.ConformanceLevel = ConformanceLevel.Auto;
-
-
- this._XmlReader = System.Xml.XmlReader.Create(this._XmlTextReader, this._XmlReaderSettings);
-
-
-
- while (this._XmlReader.Read())
- {
-
- }
- }
- catch (XmlException _XmlException)
- {
- this._ValidationError = _XmlException.Message;
- }
- catch (XmlSchemaException _XmlSchemaException)
- {
- this._ValidationError = _XmlSchemaException.Message;
- }
- catch (Exception _Exception)
- {
- this._ValidationError = _Exception.Message;
- }
-
-
- if (this._ValidationError.Trim().ToString() != string.Empty)
- {
- _StartIndex = this._ValidationError.IndexOf("An error occurred at");
- _EndIndex = this._ValidationError.Length-(this._ValidationError.Length-_StartIndex);
-
- this._ValidationError = this._ValidationError.Substring(0,_EndIndex);
- }
-
- return this._ValidationError;
- }
- #endregion
-
- #region Validation Errors
- public static void ValidationErrors(object sender, ValidationEventArgs args)
- {
-
- }
- #endregion
- }
- }
4. XmlAndSchemaValidator Tester Application Validation Windows Form Source Code
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
-
- namespace XmlAndSchemaValidator.Tester
- {
- public partial class ValidationForm : Form
- {
- #region Attibutes
- private DialogResult _DialogResult;
- private XmlAndSchemaValidator.Validator _Validator = null;
- #endregion
-
- #region Object Constructor
- public ValidationForm()
- {
- InitializeComponent();
- }
- #endregion
-
- #region Events
- #region bntSelectXmlFile_Click
- private void bntSelectXmlFile_Click(object sender, EventArgs e)
- {
- string _ErrorMsg = string.Empty;
-
- try
- {
- this.txtXmlFile.Text = string.Empty;
-
- this.ofdXmlFile = new OpenFileDialog();
- this.ofdXmlFile.Filter = "Xml Files (*.xml)|*.xml|All Files (*.*)|*.*";
- this.ofdXmlFile.Title = "Select Xml file for Schema validation";
- this._DialogResult = this.ofdXmlFile.ShowDialog();
-
- if (this._DialogResult == System.Windows.Forms.DialogResult.OK)
- {
- if (this.ofdXmlFile.FileName != string.Empty)
- {
- this.txtXmlFile.Text = this.ofdXmlFile.FileName.ToString().Trim();
- }
- }
- }
- catch (Exception _Exception)
- {
- _ErrorMsg = string.Empty;
- _ErrorMsg = "*************** Error ***************" + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> Event: bntSelectXmlFile_Click\r\n";
- _ErrorMsg = _ErrorMsg + " -> Message: " + _Exception.Message.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> Stack Trace: " + _Exception.StackTrace.ToString() + "\r\n";
-
- if (_Exception.InnerException != null)
- {
- _ErrorMsg = _ErrorMsg + " -> InnerException Message: " + _Exception.InnerException.Message.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> InnerException Stack Trace: " + _Exception.InnerException.StackTrace.ToString() + "\r\n";
- }
-
- _ErrorMsg = "*************************************";
-
- MessageBox.Show(_ErrorMsg, "XmlAndSchemaValidator", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- #endregion
-
- #region bntSelectXsdFile_Click
- private void bntSelectXsdFile_Click(object sender, EventArgs e)
- {
- string _ErrorMsg = string.Empty;
-
- try
- {
- this.txtXsdFile.Text = string.Empty;
-
- this.ofdXsdFile = new OpenFileDialog();
- this.ofdXsdFile.Filter = "Xsd Files (*.Xsd)|*.Xsd|All Files (*.*)|*.*";
- this.ofdXsdFile.Title = "Select Xsd file to use in validation";
- this._DialogResult = this.ofdXsdFile.ShowDialog();
-
- if (this._DialogResult == System.Windows.Forms.DialogResult.OK)
- {
- if (this.ofdXsdFile.FileName != string.Empty)
- {
- this.txtXsdFile.Text = this.ofdXsdFile.FileName.ToString().Trim();
- }
- }
- }
- catch (Exception _Exception)
- {
- _ErrorMsg = string.Empty;
- _ErrorMsg = "*************** Error ***************" + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> Event: bntSelectXsdFile_Click\r\n";
- _ErrorMsg = _ErrorMsg + " -> Message: " + _Exception.Message.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> Stack Trace: " + _Exception.StackTrace.ToString() + "\r\n";
-
- if (_Exception.InnerException != null)
- {
- _ErrorMsg = _ErrorMsg + " -> InnerException Message: " + _Exception.InnerException.Message.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> InnerException Stack Trace: " + _Exception.InnerException.StackTrace.ToString() + "\r\n";
- }
-
- _ErrorMsg = "*************************************";
-
- MessageBox.Show(_ErrorMsg, "XmlAndSchemaValidator", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- #endregion
-
- #region bntValidate_Click
- private void bntValidate_Click(object sender, EventArgs e)
- {
- string _ErrorMsg = string.Empty;
- string _ValidatorErrorMsg = string.Empty;
- FileInfo _FileInfo = null;
-
- try
- {
- this.txtValidationResult.Text = string.Empty;
-
- _FileInfo = new FileInfo(this.txtXmlFile.Text);
- this._Validator = new XmlAndSchemaValidator.Validator();
- _ValidatorErrorMsg = this._Validator.Validate(3, _FileInfo, System.Xml.XmlNodeType.Element, this.txtTargetNameSpace.Text, this.txtXsdFile.Text);
-
- if (_ValidatorErrorMsg != string.Empty)
- {
- _ErrorMsg = string.Empty;
- _ErrorMsg = "*************** Validation Error ***************" + "\r\n";
- _ErrorMsg = _ErrorMsg + "Validation Message: " + _ValidatorErrorMsg.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + "************************************************";
-
- this.txtValidationResult.AppendText(_ErrorMsg);
- }
- else
- {
- _ErrorMsg = string.Empty;
- _ErrorMsg = "*************** Validation Sucess ***************" + "\r\n";
- _ErrorMsg = _ErrorMsg + "No Validation error ocorred!!!\r\n";
- _ErrorMsg = _ErrorMsg + "************************************************";
-
- this.txtValidationResult.AppendText(_ErrorMsg);
- }
- }
- catch (Exception _Exception)
- {
- _ErrorMsg = string.Empty;
- _ErrorMsg = "*************** Error ***************" + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> Event: bntValidate_Click\r\n";
- _ErrorMsg = _ErrorMsg + " -> Message: " + _Exception.Message.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> Stack Trace: " + _Exception.StackTrace.ToString() + "\r\n";
-
- if (_Exception.InnerException != null)
- {
- _ErrorMsg = _ErrorMsg + " -> InnerException Message: " + _Exception.InnerException.Message.ToString() + "\r\n";
- _ErrorMsg = _ErrorMsg + " -> InnerException Stack Trace: " + _Exception.InnerException.StackTrace.ToString() + "\r\n";
- }
-
- _ErrorMsg = _ErrorMsg + "*************************************";
-
- MessageBox.Show(_ErrorMsg, "XmlAndSchemaValidator", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- #endregion
- #endregion
- }
- }
Finally the tester application should behave like this:
5. Conclution
Thank you for your care provided during reading my article and I hope you have been helped in some way.