in C#,
// xsv.cs
// ------------------------------------------------------------------
//
// Validate an XML document against a schema.
//
// last saved:
// Time-stamp: <2010-May-06 00:28:44>
// ------------------------------------------------------------------
//
// Copyright (c) 2010 by Dino Chiesa
// All rights reserved!
//
// ------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Reflection;
[assembly: AssemblyTitle("Cheeso.Tools.XmlSchemaValidator")]
[assembly: AssemblyDescription("Xml Schema Validator")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright © Dino Chiesa 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.1.1")]
namespace Cheeso.Tools
{
public class XmlSchemaValidator
{
String _xsdfile;
String _xmlfile;
private void Validate()
{
List<String> validationErrors = new List<String>();
List<String> validationWarnings = new List<String> ();
Action<object, ValidationEventArgs> handler = (obj, args) => {
if (args.Severity==XmlSeverityType.Warning)
validationWarnings.Add(args.Message);
else
validationErrors.Add(args.Message);
};
XmlTextReader tr = new XmlTextReader(_xmlfile);
XmlReaderSettings settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema
};
settings.Schemas.Add(null, _xsdfile);
settings.ValidationEventHandler +=
new ValidationEventHandler(handler);
XmlReader reader = XmlReader.Create(tr, settings);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(reader);
// Check results
if (validationErrors.Count > 0)
{
validationErrors.ForEach(Console.WriteLine);
Console.WriteLine("The XML document is not valid, according to that Schema.");
}
else
{
if (validationWarnings.Count > 0)
{
validationWarnings.ForEach(Console.WriteLine);
}
Console.WriteLine("The XML document is valid, according to that Schema.");
}
}
public static void Usage()
{
Console.WriteLine("\nxsv: validate an XML document against an XML Schema.\n");
Console.WriteLine("Usage:\n xsv <xmldoc> <xmlschema>");
System.Environment.Exit(0);
}
public XmlSchemaValidator (string[] args)
{
for (int i=0; i < args.Length; i++)
{
if (args[i] == "-h" ||
args[i] == "--help" ||
args[i] == "-?")
{
Usage();
}
if (_xmlfile == null)
_xmlfile = args[i];
else if (_xsdfile == null)
_xsdfile = args[i];
else
Usage();
}
// default values
if (_xmlfile == null || _xsdfile == null)
Usage();
}
public static void Main(string[] args)
{
try
{
new XmlSchemaValidator(args)
.Validate();
}
catch (System.Exception exc1)
{
Console.WriteLine("Exception: {0}", exc1.ToString());
Usage();
}
}
}
}