Simple XML validation helper using XmlReader
Purpose: simply validate a xml file against a xsd file, in C#.
It can be used in two ways:
1- Static single line call:
bool success = XMLValidationHelper.Validate("myFile.xml", "mySchema.xsd");
2- Using helper object to collect the first error message occured:
XMLValidationHelper validator = new XMLValidationHelper("myFile.xml", "mySchema.xsd");
validator.Validate();
if (!validator.IsValid)
{
// do something...
}
Here is the class:
using System;
using System.Xml;
using System.Xml.Schema;
using System.Text;
/// <summary>
/// Helper class to check a XML against a XSD file
/// </summary>
public class XMLValidationHelper
{
string xmlFileName, xsdFileName;
string exceptionMessage;
bool isValid = false;
public string ExceptionMessage
{
get { return exceptionMessage; }
set { exceptionMessage = value; }
}
public XMLValidationHelper(string xmlFileName, string xsdFileName)
{
this.xmlFileName = xmlFileName;
this.xsdFileName = xsdFileName;
}
/// <summary>
/// Global validation state of the xml against the xsd
/// </summary>
public bool IsValid
{
get { return isValid; }
set { isValid = value; }
}
/// <summary>
/// Read the document and collects the validation exceptions if any.
/// </summary>
/// <returns></returns>
public bool Validate()
{
XmlReader schemaReader = XmlReader.Create(this.xsdFileName);
/// validation settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags =
System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add("", schemaReader);
XmlReader myReader = XmlReader.Create(this.xmlFileName, settings);
this.isValid = true;
try
{
while (!myReader.EOF)
myReader.Read();
}
catch (System.Xml.Schema.XmlSchemaException validationException)
{
this.isValid = false;
this.exceptionMessage = validationException.Message;
}
finally
{
schemaReader.Close();
myReader.Close();
}
return this.isValid;
}
public static bool Validate(string xmlFileName, string xsdFileName)
{
XMLValidationHelper instantHelper = new XMLValidationHelper(xmlFileName, xsdFileName);
return instantHelper.Validate();
}
}
No comments:
Post a Comment