How to validate a XML file against a XSD file, including the referenced schemas by the XSD file in C#.

If you want to validate an XML file against a XSD file and use the XSD schemas referenced by the XSD file in the validation, you can use the following C# code:

 

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Research.Rli
{
/// <summary>
/// Tests in this class are only used to analyse and research code.
/// It is not intended to contain real integration tests.
/// </summary>
[TestClass]
public class RliResearchTester
{
public RliResearchTester()
{
}
/// <summary>
/// Test xml validation against a XSD file.
/// </summary>
[TestMethod]
public void ValidateXmlTest()
{
ValidateXml(@"C:\Data\Input.xml", @"C:\Data\ValidationSchema.xsd");
}
/// <summary>
/// Validates a xml file (found at the given xmlFilePath) to a XSD file (found at the given xsdFilePath).
/// </summary>
/// <param name="xmlFilePath">The xml file to validate.</param>
/// <param name="xsdFilePath">The xsd file used in the validation.</param>
/// <exception cref="ArgumentNullException">
/// Throws an ArgumentNullException, when xmlFilePath is null, empty or contains only white spaces.
/// </exception>
/// <exception cref="ArgumentNullException">
/// Throws an ArgumentNullException, when xsdFilePath is null, empty or contains only white spaces.
/// </exception>
/// <exception cref="ArgumentException">Throws an ArgumentException, when xmlFilePath does not exist.</exception>
/// <exception cref="ArgumentException">Throws an ArgumentException, when xsdFilePath does not exist.</exception>
/// <remarks>
/// - Includes schemas referenced by the given xsd file (recursively).
/// </remarks>
public void ValidateXml(string xmlFilePath, string xsdFilePath)
{
if (string.IsNullOrWhiteSpace(xmlFilePath)) { throw new ArgumentNullException("xmlFilePath"); }
if (string.IsNullOrWhiteSpace(xsdFilePath)) { throw new ArgumentNullException("xsdFilePath"); }
if (!File.Exists(xmlFilePath))
{
throw new ArgumentException(string.Format("File [{0}] not found.", xmlFilePath));
}
if (!File.Exists(xsdFilePath))
{
throw new ArgumentException(string.Format("File [{0}] not found.", xsdFilePath));
}
var schemas = new XmlSchemaSet();
// Use the target namespace specified in the XSD file. 
schemas.Add(null, xsdFilePath);
var readerSettings = new XmlReaderSettings();
// Validate the xml file to an XSD file not an DTD or XDR.
readerSettings.ValidationType = ValidationType.Schema;
// Include schemas referenced by the given xsd file (recursively) in the validation proces.
readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
// Warnings will fire the ValidationEventHandler function.
readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
readerSettings.Schemas.Add(schemas);
// The function [ValidationEventHandler] will be used to handle all validation errors / warnings.
readerSettings.ValidationEventHandler += ValidationEventHandler;
using (var xmlReader = XmlReader.Create(xmlFilePath, readerSettings))
{
while (xmlReader.Read()) { }    // Validate XML file.
}
}
/// <summary>
/// This event will fire on every XML validation error / warning.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void ValidationEventHandler(object sender, ValidationEventArgs args)
{
Console.WriteLine(string.Format("",
new object[] { args.Exception, args.Exception.LineNumber, args.Exception.LinePosition }));
}
}
}

3 Comments

  1. Pingback: How to read through whole xml and get all exception(s) by comparing with a schema file in asp.net with c#? | shareitHQ

  2. Abbid Siddiqui

    Nice article, however, I’m having the following error while using reader.Read()
    “Index (zero based) must be greater than or equal to zero and less than the size of the argument list”

    Can you please help me out on this?

Leave a Reply

Your email address will not be published. Required fields are marked *