SHARE
Facebook X Pinterest WhatsApp

Validation of XML with XSD

Introduction This article explains about how to validate an XML document with XSD schema. The validation is performed by checking whether the XML document is a well-formed one by programmatically using .NET classes in C#. XML document An XML document contains elements, attributes, and values of primitive data types. For example, consider the following XML […]

Written By
thumbnail
CodeGuru Staff
CodeGuru Staff
Mar 24, 2004
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Introduction

This article explains about how to validate an XML document with XSD schema. The validation is performed by checking whether the XML document is a well-formed one by programmatically using .NET classes in C#.

XML document

An XML document contains elements, attributes, and values of primitive data types. For example, consider the following XML document:

<address xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi_noNamespaceSchemaLocation="address.xsd">
<name>John Smith</name>
<street>109 Abbey Close</street>
<city>Hayes</city>
<country> UK</country>
</address>

XSD schema

XSD schema defines elements, attributes, and the relationship between them. It conforms to the W3C XML schema standards and recommendations. XSD schema for the above XML document, address.xsd, can be given as follows:

<xs:schema xmlns_xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city"type="xs:string"/>
<xs:element name="country"type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Validation event handler

The ValidationEventHandler event is used to define an event handler for receiving the notification about XSD schema validation errors. The validation errors and warnings are reported through the ValidationEventHandler call-back function. If any validation error occurs, an exception is thrown, and the XmlValidatingReader cannot be restarted.

XML validation with .NET classes

Microsoft .NET framework classes support the W3C XML schema recommendation. The classes used to validate the XML document are XmlTextReader, XmlSchemaCollection, and XmlValidatingReader. The sequence of steps to validate an XML document is given as follows:

  1. The ValidationHandler event handler method is defined.
  2. The XSD schema is being parsed using XmlTextReader class.
  3. The parsed schema is added to the schema collection using XmlSchemaCollection class.
  4. The schema collection is associated with XmlValidatingReader class.
  5. The event handler method is associated with XmlValidatingReader class.
  6. XmlValidatingReader class validates the XML document using the namespace URI specified when the schema was added to the collection.

Sample Code

The following example shows how to validate XML document against XSD schema by using Microsoft .NET framework classes.

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;

public class XMLValidator
{
    // Validation Error Count
    static int ErrorsCount = 0;

     // Validation Error Message
    static string ErrorMessage = "";

    public static void ValidationHandler(object sender,
                                         ValidationEventArgs args)
    {
        ErrorMessage = ErrorMessage + args.Message + "\r\n";
        ErrorsCount ++;
    }

    public void Validate(string strXMLDoc)
    {
        try
        {
            // Declare local objects
            XmlTextReader         tr   = null;
            XmlSchemaCollection   xsc  = null;
            XmlValidatingReader   vr   = null;

            // Text reader object
            tr  = new XmlTextReader(urlpath);
            xsc = new XmlSchemaCollection();
            xsc.Add(null, tr);

            // XML validator object

            vr = new XmlValidatingReader( strXMLDoc,
                         XmlNodeType.Document, null);

            vr.Schemas.Add(xsc);

            // Add validation event handler

            vr.ValidationType = ValidationType.Schema;
            vr.ValidationEventHandler +=
                     new ValidationEventHandler(ValidationHandler);

            // Validate XML data

            while(vr.Read());

            vr.Close();

            // Raise exception, if XML validation fails
            if (ErrorsCount > 0)
            {
                throw new Exception(ErrorMessage);
            }

            // XML Validation succeeded
            Console.WriteLine("XML validation succeeded.\r\n");
        }
        catch(Exception error)
        {
            // XML Validation failed
            Console.WriteLine("XML validation failed." + "\r\n" +
            "Error Message: " + error.Message);
        }
    }
}

Conclusion

This article explained about the XML document, XSD schema, and how to validate XML document against XSD schema using Microsoft .NET framework classes.

Author:
Syed Hameed
Wipro Technologies
Bangalore



Recommended for you...

C# vs Java
Nicholas Rini
Mar 24, 2023
C# versus C
Nicholas Rini
Mar 22, 2023
Different Types of JIT Compilers in .NET
Tariq Siddiqui
Mar 17, 2023
Middleware in ASP.NET Core
Tariq Siddiqui
Mar 16, 2023
CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.