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