Tuesday, January 26, 2010

Console XML/XSD Validation Application

Could not find a decent console application to validate an XML file against multiple XSD Schema Documents so I decided to write one and share for any who may need it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Schema;

namespace XmlValidator
{
class Program
{
static void Main(string[] args)
{
int result = 0;
string documentPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, args[0]);
if (!File.Exists(documentPath)) throw new Exception(String.Format("The document '{0}' does not exist", documentPath));
List schemaPaths = new List();
foreach (string path in args.Skip(1))
{
string schemaPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, path);
if (!File.Exists(schemaPath)) throw new Exception(String.Format("The schema document '{0}' does not exist", schemaPath));
schemaPaths.Add(schemaPath);
}
using (Stream stream = File.Open(documentPath,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(
delegate(object sender, ValidationEventArgs e)
{
result = -1;
Console.Write("Line:");
Console.Write(e.Exception.LineNumber);
Console.Write(" Position:");
Console.Write(e.Exception.LinePosition);
Console.Write(" ");
Console.Write(e.Severity.ToString("G"));
Console.Write(" ");
Console.WriteLine(e.Message);

}
);
foreach (string path in schemaPaths) settings.Schemas.Add(XmlSchema.Read(XmlReader.Create(path), null));
stream.Position = 0;
XmlReader validator = XmlReader.Create(stream, settings);
while (validator.Read()) ;
validator.Close();
}
if (result == 0) Console.WriteLine("Document is valid");
#if DEBUG
Console.ReadLine();
#endif
Environment.Exit(result);
}
}
}

1 comment: