C# Source - XMLValidator
This is a simple little command-line tool for validating an XML file against an xml schema. Takes two arguments the first being the XML file and the second being the XSD Schema.
using System;
using System.Xml;
using System.Xml.Schema;
namespace xmlValidator
{
class Program
{
private static System.Boolean m_success;
private const string PRG_NAME = "xmlValidator Program - v 0.99.00";
private const string CPY_RGHT = "Copyright (c) 2009 - ";
private const string AUTHOR = "John Wicks";
private const string USAGE = "Usage: xmlValidator xmlFile xmlSchema";
static void Main(string[] args)
{
XmlTextReader myXmlText = null;
XmlValidatingReader myReader = null;
XmlSchemaCollection mySchema = new XmlSchemaCollection();
ValidationEventHandler myEventHandler = new ValidationEventHandler(Program.ShowErrors);
if (args.Length != 2)
{
ShowCopyright();
}
else
{
try
{
myXmlText = new XmlTextReader(args[0]);
//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
//Implement the reader.
myReader = new XmlValidatingReader(myXmlText);
//Add the schema.
mySchema.Add(null, args[1]);
//Set the schema type and add the schema to the reader.
myReader.ValidationType = ValidationType.Schema;
myReader.Schemas.Add(mySchema);
while (myReader.Read())
{
}
Console.WriteLine("XML document {0} validated\r\nagainst the schema {1}.", args[0], args[1]);
}
catch (XmlException XmlExp)
{
Console.WriteLine(XmlExp.Message);
}
catch (XmlSchemaException XmlSchExp)
{
Console.WriteLine(XmlSchExp.Message);
}
catch (Exception GenExp)
{
Console.WriteLine(GenExp.Message);
}
finally
{
Console.Read();
}
}
}
public static void ShowErrors(object sender, ValidationEventArgs args)
{
Console.WriteLine("Validation Error: {0}", args.Message);
}
public static void ShowCopyright()
{
Console.WriteLine("{0}", PRG_NAME);
Console.WriteLine("{0}{1}", CPY_RGHT, AUTHOR);
Console.WriteLine("{0}", USAGE);
}
}
}




