Xml and Schema Validator

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
  1. using System;  
  2. using System.Xml;  
  3. using System.Xml.Schema;  
  4. using System.IO;  
  5. using System.Text;  
  6.   
  7. namespace XmlAndSchemaValidator  
  8. {  
  9.     public class Validator  
  10.     {  
  11.         #region Attributes  
  12.         private System.Xml.XmlTextReader _XmlTextReader = null;  
  13.         private System.Xml.XmlReader _XmlReader = null;  
  14.         private System.Xml.XmlReaderSettings _XmlReaderSettings = null;  
  15.         private System.Xml.XmlParserContext _XmlParserContext = null;  
  16.         private System.Xml.Schema.XmlSchemaSet _XmlSchemaSet = null;  
  17.         private string _ValidationError = string.Empty;  
  18.         #endregion  
  19.  
  20.         #region Object Constructor  
  21.         public Validator()  
  22.         {  
  23.             this._XmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();  
  24.             this._XmlParserContext = new System.Xml.XmlParserContext(nullnull"", XmlSpace.None);  
  25.   
  26.             ValidationEventHandler _ValidationEventHandler = new ValidationEventHandler(ValidationErrors);  
  27.         }  
  28.         #endregion  
  29.  
  30.         #region Validate  
  31.         // This Method will validate a Xml File  
  32.         public string Validate(Int32 _EncodingType, FileInfo _XmlFile, XmlNodeType _XmlNodeType, string _Namespace, string _URI)  
  33.         {  
  34.             System.Text.UTF8Encoding _UTF8Encoding = new System.Text.UTF8Encoding();  
  35.             System.Text.UTF32Encoding _UTF32Encoding = new System.Text.UTF32Encoding();  
  36.             System.Text.Encoding _Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");  
  37.             Int32 _StartIndex = 0;  
  38.             Int32 _EndIndex = 0;  
  39.             string _XmlString = string.Empty;  
  40.             Byte[] _Buffer = null;  
  41.             FileStream _FileStream = null;        
  42.   
  43.             try  
  44.             {  
  45.                 // Verifies if the Xml file exists on the filesystem  
  46.                 if (_XmlFile.Exists)  
  47.                 {  
  48.                     try  
  49.                     {  
  50.                         _FileStream = _XmlFile.OpenRead();  
  51.                         _Buffer = new Byte[_FileStream.Length];  
  52.   
  53.                         _FileStream.Read(_Buffer, 0, _Buffer.Length);  
  54.   
  55.                         // Read the Xml file content with a pre-determinated encoding  
  56.                         switch (_EncodingType.ToString())  
  57.                         {  
  58.                             case "1":  
  59.                                 _XmlString = _UTF8Encoding.GetString(_Buffer);  
  60.                                 break;  
  61.   
  62.                             case "2":  
  63.                                 _XmlString = _UTF32Encoding.GetString(_Buffer);  
  64.                                 break;  
  65.   
  66.                             case "3":  
  67.                                 _XmlString = _Encoding.GetString(_Buffer);  
  68.                                 break;  
  69.                         }  
  70.   
  71.                         _XmlString = _XmlString.Replace("\r""");  
  72.                         _XmlString = _XmlString.Replace("\n""");  
  73.                         _XmlString = _XmlString.Replace("\t""");  
  74.   
  75.                         _FileStream.Close();  
  76.                     }  
  77.                     catch  
  78.                     {  
  79.                         _FileStream.Close();  
  80.                     }  
  81.                 }  
  82.   
  83.                 // Add the NameSpace and the Schema file for validation  
  84.                 this._XmlSchemaSet.Add(_Namespace, _URI);  
  85.   
  86.                 // Creates the XmlTextReader based on the Xml file content  
  87.                 this._XmlTextReader = new XmlTextReader(_XmlString, _XmlNodeType, this._XmlParserContext);  
  88.                 this._XmlTextReader.Read();  
  89.   
  90.                 // Setup XmlReaderSettings  
  91.                 this._XmlReaderSettings = new System.Xml.XmlReaderSettings();  
  92.                 this._XmlReaderSettings.ValidationType = ValidationType.Schema;  
  93.                 this._XmlReaderSettings.IgnoreComments = true;  
  94.                 this._XmlReaderSettings.IgnoreWhitespace = true;  
  95.   
  96.                 // Add the NameSpace and the Schema file for validation  
  97.                 this._XmlReaderSettings.Schemas.Add(_Namespace, _URI);  
  98.                   
  99.                 // ConformanceLevel Auto indicates that the XML writer should determine the level of conformance  
  100.                 this._XmlReaderSettings.ConformanceLevel = ConformanceLevel.Auto;  
  101.   
  102.                 // Creates a XmlReader based on the information gathered on XmlTextReader and assumes the XmlReaderSettings  
  103.                 this._XmlReader = System.Xml.XmlReader.Create(this._XmlTextReader, this._XmlReaderSettings);  
  104.   
  105.                 // This step will read all Xml file and throw an exception when the  
  106.                 // xml file is not valid  
  107.                 while (this._XmlReader.Read())  
  108.                 {  
  109.   
  110.                 }  
  111.             }  
  112.             catch (XmlException _XmlException)  
  113.             {  
  114.                 this._ValidationError = _XmlException.Message;  
  115.             }  
  116.             catch (XmlSchemaException _XmlSchemaException)  
  117.             {  
  118.                 this._ValidationError = _XmlSchemaException.Message;  
  119.             }  
  120.             catch (Exception _Exception)  
  121.             {  
  122.                 this._ValidationError = _Exception.Message;  
  123.             }  
  124.   
  125.             // Manipulate the error message  
  126.             if (this._ValidationError.Trim().ToString() != string.Empty)  
  127.             {  
  128.                 _StartIndex = this._ValidationError.IndexOf("An error occurred at");  
  129.                 _EndIndex = this._ValidationError.Length - (this._ValidationError.Length - _StartIndex);  
  130.   
  131.                 if (_StartIndex >= 0)  
  132.                     this._ValidationError = this._ValidationError.Substring(0, _EndIndex);  
  133.             }  
  134.   
  135.             return this._ValidationError;  
  136.         }  
  137.   
  138.         // This Method will validate a Xml String  
  139.         public string Validate(string _XmlString, XmlNodeType _XmlNodeType, string _Namespace, string _URI)  
  140.         {             
  141.             Int32 _StartIndex = 0;  
  142.             Int32 _EndIndex = 0;  
  143.   
  144.             try  
  145.             {  
  146.                 // Add the NameSpace and the Schema file for validation  
  147.                 this._XmlSchemaSet.Add(_Namespace, _URI);  
  148.   
  149.                 // Creates the XmlTextReader based on the Xml file content  
  150.                 this._XmlTextReader = new XmlTextReader(_XmlString, _XmlNodeType, this._XmlParserContext);  
  151.                 this._XmlTextReader.Read();  
  152.   
  153.                 // Setup XmlReaderSettings  
  154.                 this._XmlReaderSettings = new System.Xml.XmlReaderSettings();  
  155.                 this._XmlReaderSettings.ValidationType = ValidationType.Schema;  
  156.                 this._XmlReaderSettings.IgnoreComments = true;  
  157.                 this._XmlReaderSettings.IgnoreWhitespace = true;  
  158.   
  159.                 // Add the NameSpace and the Schema file for validation  
  160.                 this._XmlReaderSettings.Schemas.Add(_Namespace, _URI);  
  161.   
  162.                 // ConformanceLevel Auto indicates that the XML writer should determine the level of conformance  
  163.                 this._XmlReaderSettings.ConformanceLevel = ConformanceLevel.Auto;  
  164.   
  165.                 // Creates a XmlReader based on the information gathered on XmlTextReader and assumes the XmlReaderSettings  
  166.                 this._XmlReader = System.Xml.XmlReader.Create(this._XmlTextReader, this._XmlReaderSettings);  
  167.   
  168.                 // This step will read all Xml file and throw an exception when the  
  169.                 // xml file is not valid  
  170.                 while (this._XmlReader.Read())  
  171.                 {  
  172.   
  173.                 }                 
  174.             }  
  175.             catch (XmlException _XmlException)  
  176.             {  
  177.                 this._ValidationError = _XmlException.Message;  
  178.             }  
  179.             catch (XmlSchemaException _XmlSchemaException)  
  180.             {  
  181.                 this._ValidationError = _XmlSchemaException.Message;  
  182.             }  
  183.             catch (Exception _Exception)  
  184.             {  
  185.                 this._ValidationError = _Exception.Message;  
  186.             }  
  187.   
  188.             // Manipulate the error message  
  189.             if (this._ValidationError.Trim().ToString() != string.Empty)  
  190.             {  
  191.                 _StartIndex = this._ValidationError.IndexOf("An error occurred at");  
  192.                 _EndIndex = this._ValidationError.Length-(this._ValidationError.Length-_StartIndex);  
  193.   
  194.                 this._ValidationError = this._ValidationError.Substring(0,_EndIndex);  
  195.             }  
  196.   
  197.             return this._ValidationError;  
  198.         }  
  199.         #endregion  
  200.  
  201.         #region Validation Errors  
  202.         public static void ValidationErrors(object sender, ValidationEventArgs args)  
  203.         {  
  204.               
  205.         }  
  206.         #endregion  
  207.     }  
  208. }  
4. XmlAndSchemaValidator Tester Application Validation Windows Form Source Code
  1. using System;  
  2. using System.IO;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel;  
  5. using System.Data;  
  6. using System.Drawing;  
  7. using System.Linq;  
  8. using System.Text;  
  9. using System.Windows.Forms;  
  10.   
  11. namespace XmlAndSchemaValidator.Tester  
  12. {  
  13.     public partial class ValidationForm : Form  
  14.     {  
  15.         #region Attibutes  
  16.         private DialogResult _DialogResult;  
  17.         private XmlAndSchemaValidator.Validator _Validator = null;  
  18.         #endregion  
  19.  
  20.         #region Object Constructor  
  21.         public ValidationForm()  
  22.         {  
  23.             InitializeComponent();  
  24.         }  
  25.         #endregion          
  26.  
  27.         #region Events  
  28.         #region bntSelectXmlFile_Click  
  29.         private void bntSelectXmlFile_Click(object sender, EventArgs e)  
  30.         {  
  31.             string _ErrorMsg = string.Empty;  
  32.               
  33.             try  
  34.             {  
  35.                 this.txtXmlFile.Text = string.Empty;  
  36.   
  37.                 this.ofdXmlFile = new OpenFileDialog();  
  38.                 this.ofdXmlFile.Filter = "Xml Files (*.xml)|*.xml|All Files (*.*)|*.*";  
  39.                 this.ofdXmlFile.Title = "Select Xml file for Schema validation";  
  40.                 this._DialogResult = this.ofdXmlFile.ShowDialog();  
  41.   
  42.                 if (this._DialogResult == System.Windows.Forms.DialogResult.OK)  
  43.                 {  
  44.                     if (this.ofdXmlFile.FileName != string.Empty)  
  45.                     {  
  46.                         this.txtXmlFile.Text = this.ofdXmlFile.FileName.ToString().Trim();  
  47.                     }  
  48.                 }  
  49.             }  
  50.             catch (Exception _Exception)  
  51.             {                 
  52.                 _ErrorMsg = string.Empty;  
  53.                 _ErrorMsg = "*************** Error ***************" + "\r\n";  
  54.                 _ErrorMsg = _ErrorMsg + " -> Event: bntSelectXmlFile_Click\r\n";  
  55.                 _ErrorMsg = _ErrorMsg + " -> Message: " + _Exception.Message.ToString() + "\r\n";  
  56.                 _ErrorMsg = _ErrorMsg + " -> Stack Trace: " + _Exception.StackTrace.ToString() + "\r\n";  
  57.   
  58.                 if (_Exception.InnerException != null)  
  59.                 {  
  60.                     _ErrorMsg = _ErrorMsg + " -> InnerException Message: " + _Exception.InnerException.Message.ToString() + "\r\n";  
  61.                     _ErrorMsg = _ErrorMsg + " -> InnerException Stack Trace: " + _Exception.InnerException.StackTrace.ToString() + "\r\n";  
  62.                 }  
  63.   
  64.                 _ErrorMsg = "*************************************";  
  65.   
  66.                 MessageBox.Show(_ErrorMsg, "XmlAndSchemaValidator", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  67.             }  
  68.         }  
  69.         #endregion  
  70.  
  71.         #region bntSelectXsdFile_Click  
  72.         private void bntSelectXsdFile_Click(object sender, EventArgs e)  
  73.         {  
  74.             string _ErrorMsg = string.Empty;  
  75.   
  76.             try  
  77.             {  
  78.                 this.txtXsdFile.Text = string.Empty;  
  79.   
  80.                 this.ofdXsdFile = new OpenFileDialog();  
  81.                 this.ofdXsdFile.Filter = "Xsd Files (*.Xsd)|*.Xsd|All Files (*.*)|*.*";  
  82.                 this.ofdXsdFile.Title = "Select Xsd file to use in validation";  
  83.                 this._DialogResult = this.ofdXsdFile.ShowDialog();  
  84.   
  85.                 if (this._DialogResult == System.Windows.Forms.DialogResult.OK)  
  86.                 {  
  87.                     if (this.ofdXsdFile.FileName != string.Empty)  
  88.                     {  
  89.                         this.txtXsdFile.Text = this.ofdXsdFile.FileName.ToString().Trim();  
  90.                     }  
  91.                 }  
  92.             }  
  93.             catch (Exception _Exception)  
  94.             {  
  95.                 _ErrorMsg = string.Empty;  
  96.                 _ErrorMsg = "*************** Error ***************" + "\r\n";  
  97.                 _ErrorMsg = _ErrorMsg + " -> Event: bntSelectXsdFile_Click\r\n";  
  98.                 _ErrorMsg = _ErrorMsg + " -> Message: " + _Exception.Message.ToString() + "\r\n";  
  99.                 _ErrorMsg = _ErrorMsg + " -> Stack Trace: " + _Exception.StackTrace.ToString() + "\r\n";  
  100.   
  101.                 if (_Exception.InnerException != null)  
  102.                 {  
  103.                     _ErrorMsg = _ErrorMsg + " -> InnerException Message: " + _Exception.InnerException.Message.ToString() + "\r\n";  
  104.                     _ErrorMsg = _ErrorMsg + " -> InnerException Stack Trace: " + _Exception.InnerException.StackTrace.ToString() + "\r\n";  
  105.                 }  
  106.   
  107.                 _ErrorMsg = "*************************************";  
  108.   
  109.                 MessageBox.Show(_ErrorMsg, "XmlAndSchemaValidator", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  110.             }  
  111.         }  
  112.         #endregion  
  113.  
  114.         #region bntValidate_Click  
  115.         private void bntValidate_Click(object sender, EventArgs e)  
  116.         {  
  117.             string _ErrorMsg = string.Empty;  
  118.             string _ValidatorErrorMsg = string.Empty;  
  119.             FileInfo _FileInfo = null;  
  120.   
  121.             try  
  122.             {  
  123.                 this.txtValidationResult.Text = string.Empty;  
  124.   
  125.                 _FileInfo = new FileInfo(this.txtXmlFile.Text);  
  126.                 this._Validator = new XmlAndSchemaValidator.Validator();  
  127.                 _ValidatorErrorMsg = this._Validator.Validate(3, _FileInfo, System.Xml.XmlNodeType.Element, this.txtTargetNameSpace.Text, this.txtXsdFile.Text);  
  128.   
  129.                 if (_ValidatorErrorMsg != string.Empty)  
  130.                 {  
  131.                     _ErrorMsg = string.Empty;  
  132.                     _ErrorMsg = "*************** Validation Error ***************" + "\r\n";  
  133.                     _ErrorMsg = _ErrorMsg + "Validation Message: " + _ValidatorErrorMsg.ToString() + "\r\n";  
  134.                     _ErrorMsg = _ErrorMsg + "************************************************";  
  135.   
  136.                     this.txtValidationResult.AppendText(_ErrorMsg);  
  137.                 }  
  138.                 else  
  139.                 {  
  140.                     _ErrorMsg = string.Empty;  
  141.                     _ErrorMsg = "*************** Validation Sucess ***************" + "\r\n";  
  142.                     _ErrorMsg = _ErrorMsg + "No Validation error ocorred!!!\r\n";  
  143.                     _ErrorMsg = _ErrorMsg + "************************************************";  
  144.   
  145.                     this.txtValidationResult.AppendText(_ErrorMsg);  
  146.                 }  
  147.             }  
  148.             catch (Exception _Exception)  
  149.             {  
  150.                 _ErrorMsg = string.Empty;  
  151.                 _ErrorMsg = "*************** Error ***************" + "\r\n";  
  152.                 _ErrorMsg = _ErrorMsg + " -> Event: bntValidate_Click\r\n";  
  153.                 _ErrorMsg = _ErrorMsg + " -> Message: " + _Exception.Message.ToString() + "\r\n";  
  154.                 _ErrorMsg = _ErrorMsg + " -> Stack Trace: " + _Exception.StackTrace.ToString() + "\r\n";  
  155.   
  156.                 if (_Exception.InnerException != null)  
  157.                 {  
  158.                     _ErrorMsg = _ErrorMsg + " -> InnerException Message: " + _Exception.InnerException.Message.ToString() + "\r\n";  
  159.                     _ErrorMsg = _ErrorMsg + " -> InnerException Stack Trace: " + _Exception.InnerException.StackTrace.ToString() + "\r\n";  
  160.                 }  
  161.   
  162.                 _ErrorMsg = _ErrorMsg + "*************************************";  
  163.   
  164.                 MessageBox.Show(_ErrorMsg, "XmlAndSchemaValidator", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  165.             }  
  166.         }  
  167.         #endregion  
  168.         #endregion  
  169.     }  
  170. }  
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.


Similar Articles