Compare XML File with XSD in C#

 

Whenever we are considering the XML as data source, first we have to validate the XML data source before proceeding further. Here validation means we have to check whether XML file has required elements and all those elements contain proper data.

 

In this article we discuss about how to validate XML file using XSD schema by taking Library example. For example we have Library.xml file as shown below.

 

Library.xml

 

<?xml version="1.0" encoding="utf-8" ?>

<Library>

  <Book>

    <Id>1</Id>

    <Name>A</Name>

  </Book>

  <Book>

    <Id>2</Id>

    <Name>B</Name>

  </Book>

  <Book>

    <Id>3</Id>

    <Name>C</Name>

  </Book>

</Library>

 

Now add Library.xsd file as shown below.

 

Library.xsd

 

<?xmlversion="1.0"encoding="utf-8"?>

<xsd:schemaid="Library"

    elementFormDefault="qualified"

    xmlns:xsd="http://www.w3.org/2001/XMLSchema"

> 

  <xsd:elementname="Library"type="LibraryType"/>

 

  <xsd:complexTypename="LibraryType">

    <xsd:sequencemaxOccurs="unbounded">

      <xsd:elementname="Book"  type="BookType"/>

    </xsd:sequence>

  </xsd:complexType>

 

  <xsd:complexTypename="BookType">

    <xsd:sequence>

      <xsd:elementname="Id"type="xsd:string"/>

      <xsd:elementname="Name"type="xsd:string"/>

    </xsd:sequence>

  </xsd:complexType>

 

</xsd:schema>

 

Now compare the Library.xml with Library.xsd as shown below.

 

        private void XMLValidationCallBack(object sender, ValidationEventArgs e)

        {

            throw new Exception();

        }

 

        public bool XMLValidate(string sXMLPath, string sXSDPath)

        {

            try

            {

                XmlDocument xmld = new XmlDocument();

                xmld.Load(sXMLPath);

                xmld.Schemas.Add(null, sXSDPath);

                xmld.Validate(XMLValidationCallBack);

 

                return true;

            }

            catch (Exception ex)

            {

                return false;

            }

        }

 

        private void btnXSD_Click(object sender, EventArgs e)

        {

            if (XMLValidate("../../Library.xml", "../../Library.xsd"))

            {

                MessageBox.Show("Library Input is in Correct Format");

            }

            else

            {

                MessageBox.Show("Library Input is not in Correct Format");

            }

        }


Now try to remove the Id or Name element from any book element, run the application. Click on the button, it displays error message as “Library Input is not in Correct Format”.

                                                                                                                    CSharpXMLXSD.zip (40.03 kb)