Validate XML file aganist XSD using Asp.Net C# VB.Net

Before working with any XML or set of XML files we have to validate the XML document first to avoid unhandled exception like corrupted file, incomplete file or even partial file. How we can validate? The XML file provider must provide you an XSD file according to their XML elements. If they don’t provide then you can also create a XSD file using Visual Studio IDE. Click here to read the process from my another article. Basically XML documents are validated by the XmlReader class Create method. This method hold 2 arguments, one is the XML file path & another one is the XmlReaderSettings object which contains the XML schema definition language (XSD) schema.

To complete this example first create the below XML file:
To create an XML file right click on project from solution explorer. Select “Add New Item”. Then scroll down to bottom & select “XML File”. Save the file with the default name. Now an XML editor will open. Copy the below code into the file content.

<Home>
  <Menu text="Books" url="MenuFromXml.aspx">
    <SubMenu text="Asp.Net" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="Ajax" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="MS SQL Server 2005" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="JavaScript" url="MenuFromXml.aspx"></SubMenu>
  </Menu>
  <Menu text="Electronics"  url="MenuFromXml.aspx">
    <SubMenu text="Camera" url="MenuFromXml.aspx">
      <SubMenu text="Digital" url="MenuFromXml.aspx">
        <SubMenu text="Canon" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Kodak" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Sony" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Casio" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Fuji" url="MenuFromXml.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Film Camera" url="MenuFromXml.aspx"></SubMenu>
    </SubMenu>
    <SubMenu text="DVDs" url="MenuFromXml.aspx">
      <SubMenu text="Comedy" url="MenuFromXml.aspx">
        <SubMenu text="English" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="French" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="German" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Spanish" url="MenuFromXml.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Kids Movies" url="MenuFromXml.aspx"></SubMenu>
      <SubMenu text="Romance Movies" url="MenuFromXml.aspx"></SubMenu>
      <SubMenu text="Action Movies" url="MenuFromXml.aspx"></SubMenu>
    </SubMenu>
  </Menu>
  <Menu text="Contact Us" url="MenuFromXml.aspx"></Menu>
</Home>

Now add the XSD file in the project also. Find the code from below:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Home">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Menu">
          <xs:complexType>
            <xs:sequence minOccurs="0">
              <xs:element maxOccurs="unbounded" name="SubMenu">
                <xs:complexType>
                  <xs:sequence minOccurs="0">
                    <xs:element maxOccurs="unbounded" name="SubMenu">
                      <xs:complexType>
                        <xs:sequence minOccurs="0">
                          <xs:element maxOccurs="unbounded" name="SubMenu">
                            <xs:complexType>
                              <xs:attribute name="text" type="xs:string" use="required" />
                              <xs:attribute name="url" type="xs:string" use="required" />
                            </xs:complexType>
                          </xs:element>
                        </xs:sequence>
                        <xs:attribute name="text" type="xs:string" use="required" />
                        <xs:attribute name="url" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                  <xs:attribute name="text" type="xs:string" use="required" />
                  <xs:attribute name="url" type="xs:string" use="required" />
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="text" type="xs:string" use="required" />
            <xs:attribute name="url" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

If you can not add the XML file or XSD file in your project to test the example please follow the below Video Tutorial or download C# or VB.Net Code example from below:

Now we need to write some server code. Where we will use XmlReaderSettings object and XmlReader class Create method. Follow the below code sample:

C# Code:

    private StringBuilder sB = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string xmlPath = MapPath("XMLFile.xml");
            string xsdPath = MapPath("XMLFile.xsd");

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, XmlReader.Create(xsdPath));

            XmlReader Oreader = XmlReader.Create(xmlPath, settings);
            XmlDocument Odoc = new XmlDocument();
            Odoc.Load(Oreader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            Odoc.Validate(eventHandler);
            if (sB.ToString() == String.Empty)
                Response.Write("Validation completed successfully.");
            else
                Response.Write("Validation Failed: " + sB.ToString());
        }
    }

    public void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
        sB.Append("Error: " + args.Message);
    }

Note: Don’ forget to incorporate ValidationEventHandler deligate mathod as well as “using System.Xml;”,”using System.Xml.Schema;”,”using System.Text;” namespaces.

VB.Net Code:

    Dim sB As StringBuilder = New StringBuilder()

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim xmlPath As String = MapPath("XMLFile.xml")
            Dim xsdPath As String = MapPath("XMLFile.xsd")

            Dim settings As XmlReaderSettings = New XmlReaderSettings()
            settings.ValidationType = ValidationType.Schema
            settings.Schemas.Add(Nothing, XmlReader.Create(xsdPath))

            Dim Oreader As XmlReader = XmlReader.Create(xmlPath, settings)
            Dim Odoc As XmlDocument = New XmlDocument()
            Odoc.Load(Oreader)
            Dim eventHandler As ValidationEventHandler = New ValidationEventHandler(AddressOf ValidationEventHandler)

            Odoc.Validate(eventHandler)
            If sB.ToString() = String.Empty Then
                Response.Write("Validation completed successfully.")
            Else
                Response.Write("Validation Failed: " + sB.ToString())
            End If
        End If
    End Sub

    Public Sub ValidationEventHandler(sender As Object, args As ValidationEventArgs)

        sB.Append("Error: " + args.Message)
    End Sub

Note: Don’ forget to incorporate ValidationEventHandler deligate mathod as well as “Imports System.Xml”,”Imports System.Xml.Schema”,”Imports System.Text” namespaces.

All end’s. Now run the project. Hope you will get an output like “Validation completed successfully”.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net, XML

Leave a Reply

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

     

*