Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to validate XML file using XSD file in ASP.NET

Author: Mike Green
Download Source Code : 1366_ValidatingXMLUsingXSD.zip

We will see how we can validate XML file using XML Schema file (.xsd) in ASP.NET.

 

There are few ways to validate XML file structure but the most common and easy way is to validate it with XML Schema file. There are other tools available for XML file validation but the best approach is to use XML Schema file. ASP.NET provides support for XML validation using XML Schema file. I will use XmlTextReader and XmlValidatingReader classes available in ASP.NET achieve this task. You can also use XmlReader and XmlReaderSetting classes to validate XML file using XML Schema file.

XML Schema file is an XML type file which is used to validate XML file structure and make sure that your XML file has valid data and it will not generate any exception. XML document impose some constraints on the structure of XML file data but XML Schema file impose some additional constraints to validate XML file structure. It checks the data types for the element content and attributes.

 

  1. Open MS Visual Studio 2010
  2. File > New > Website > Visual C# or Visual Basic > ASP.NET Empty Web Site
  3. Select Web Location as File System and Click OK
  4. From Menu, Website > Add New Item > Select Web Form and Click Add.
  5. From Menu, Website > Add New Item > Select XML File (Customers.xml)=
  6. Write below in Customers.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <Customers>
           <Customer id="1">
                  <Name>James John</Name>
                  <Phone>(206) 555-9857</Phone>
                  <City>Seattle</City>
                  <State>WA</State>
           </Customer>
           <Customer id="2">
                  <Name>Philip Wilson</Name>
                  <Phone>(206) 555-8122</Phone>
                  <City>Redmond</City>
                  <State>WA</State>
           </Customer>
    </Customers>

     
  7. From Menu, Website > Add New Item > Select XML Schema (Customers.xsd)
     
  8. Write below in Customers.xsd

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
           <xs:element name="Customers">
                  <xs:complexType>
                         <xs:sequence>
                               <xs:element maxOccurs="unbounded" name="Customer">
                                      <xs:complexType>
                                             <xs:sequence>
                                                    <xs:element name="Name" type="xs:string" />
                                                    <xs:element name="Phone" type="xs:string" />
                                                    <xs:element name="City" type="xs:string" />
                                                    <xs:element name="State" type="xs:string" />
                                             </xs:sequence>
                                             <xs:attribute name="id" type="xs:unsignedByte" use="required" />
                                      </xs:complexType>
                               </xs:element>
                         </xs:sequence>
                  </xs:complexType>
           </xs:element>
    </xs:schema>
     
  9. Open code behind file and add following namespace in it

     
    C#
     
    using System.Xml;
    using System.Xml.Schema;
     
    VB.NET

    Imports System.Xml
    Imports System.Xml.Schema
     
  10. Write code below in Page Load event

    C#
     
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFile = Server.MapPath("~/Customers.xml");
        string xsdFile = Server.MapPath("~/Customers.xsd");
     
        XmlTextReader textReader = new XmlTextReader(xmlFile);
        XmlValidatingReader validatingReader = new XmlValidatingReader(textReader);
        validatingReader.Schemas.Add(null, xsdFile);
        validatingReader.ValidationType = ValidationType.Schema;
        validatingReader.ValidationEventHandler += new ValidationEventHandler(validatingReader_ValidationEventHandler);
     
        while (validatingReader.Read())
        {
            if (validatingReader.NodeType == XmlNodeType.Element)
            {
                if (validatingReader.SchemaType is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType complexType = (XmlSchemaComplexType)validatingReader.SchemaType;
                    Response.Write(validatingReader.Name + " " + complexType.Name);
                }
                else
                {
                    object innerText = validatingReader.ReadTypedValue();
                    Response.Write(validatingReader.Name + " : " + innerText.ToString() + " <br />");
                }
            }
        }
        validatingReader.Close();
    }
     
    VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim xmlFile As String = Server.MapPath("~/Customers.xml")
        Dim xsdFile As String = Server.MapPath("~/Customers.xsd")
     
        Dim textReader As New XmlTextReader(xmlFile)
        Dim validatingReader As New XmlValidatingReader(textReader)
        validatingReader.Schemas.Add(Nothing, xsdFile)
        validatingReader.ValidationType = ValidationType.Schema
        AddHandler validatingReader.ValidationEventHandler, AddressOf validatingReader_ValidationEventHandler
     
        While validatingReader.Read()
            If validatingReader.NodeType = XmlNodeType.Element Then
                If TypeOf validatingReader.SchemaType Is XmlSchemaComplexType Then
                    Dim complexType As XmlSchemaComplexType = DirectCast(validatingReader.SchemaType, XmlSchemaComplexType)
                    Response.Write(validatingReader.Name + " " + complexType.Name)
                Else
                    Dim innerText As Object = validatingReader.ReadTypedValue()
                    Response.Write(validatingReader.Name + " : " & innerText.ToString() & "<br />")
                End If
            End If
        End While
        validatingReader.Close()
    End Sub
     
    First we have established path to both XML and XML Schema files then we have created XmlTextReader object. XmlValidatingReader object is created by pasing XmlTextReader object. We have added Schema file to XmlValidatingReader object and set validation type as Schema. We have added a ValidationEventHandler. This ValidationEventHandler is defined in next step. If Schema type is XmlSchemaComplexType then we have displayed ComplexType name and if it is not then we have called the ReadTypedValue() method and show the element and its inner text.
  11. Write below ValidationEventhHandler in code

    C#
     
    public void validatingReader_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        Response.Write("Error Message : " + e.Message);
    }
     
    VB.NET

    Public Sub validatingReader_ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
        Response.Write("Error Message : " & Convert.ToString(e.Message))
    End Sub
     
  12. Browse the website 

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to use jQuery autocomplete plug-in with Generic Handler in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net