SIGN UP MEMBER LOGIN:    
ARTICLE

XML Validation with XSD Along With Custom Exception

Posted by Surya Prakash Articles | XML in C# November 01, 2011
In this article, I will discuss about validating XML against defined XSD. Prior to getting into this article, it is mandatory that one should have basic knowledge on what XML & XSD are.
Reader Level:

In this article, I will discuss about validating XML against defined XSD. Prior to getting into this article, it is mandatory that one should have basic knowledge on what XML & XSD are.

This article describes the below items:

  1. XML data validation with XSD like XML TAGS provided are present & appropriate with respect to XSD
  2. How to write custom validations like check to see email ID is valid or not
  3. How to generate XSD from XML
  4. How to generate Custom Error, when XML data validation fails
  5. How to write regular expression in XSD

Let get into a sample with below steps

  1. Step 1: Define XML
  2. Step 2: Generate/Define XSD
  3. Step 3: Write code to validate XML with XSD
  4. Step 4: Handle Exception in by defining Custom Exception

Step 1:  First define XML as follows & name the XML file as Complex.XML

<Person xmlns:ns0="http://Testing.Message">

  <Name>Surya Prakash</Name>

  <Address>Malkajgiri</Address>

  <Phone>9966537965</Phone>

  <Email>suryaprakasash.bg@gmail.com</Email>
</Person>


Step 2: How to generate XSD? Simple follow below steps

    1. Open Complex.XML file à Go to VS Menu à XML à Create Schema, this will generate XSD as below

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

<xs:schema xmlns:ns0="http://Testing.Message" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="Person">

    <xs:complexType>

      <xs:sequence>

        <xs:element name="Name" type="xs:string" />

        <xs:element name="Address" type="xs:string" />

        <xs:element name="Phone" type="xs:unsignedLong" />

        <xs:element name="Email" type="xs:string" />

      </xs:sequence>

    </xs:complexType>

  </xs:element>

</xs:schema>

    1. As we need to write code to check if Email ID is valid or not we can do this by regular expression, by changing EMAIL tag type from String to Custom Type as follows

<xs:element name="Email" type="ValidateEmail" />

    1. As we have defined custom type we need to define its structure as follows

<xs:simpleType name="ValidateEmail">

    <xs:restriction base="xs:string">

      <xs:pattern value="[A-Za-z0-9_]+([-+.'][A-Za-z0-9_]+)*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\.[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*" />

    </xs:restriction>

  </xs:simpleType>

    1. Finally our XSD file will be as

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

<xs:schema xmlns:ns0="http://Testing.Message" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="Person">

    <xs:complexType>

      <xs:sequence>

        <xs:element name="Name" type="xs:string" />

        <xs:element name="Address" type="xs:string" />

        <xs:element name="Phone" type="xs:string" />

        <xs:element name="Email" type="ValidateEmail" />

      </xs:sequence>

    </xs:complexType>

  </xs:element>

  <xs:simpleType name="ValidateEmail">

    <xs:restriction base="xs:string">

      <xs:pattern value="[A-Za-z0-9_]+([-+.'][A-Za-z0-9_]+)*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\.[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*" />

    </xs:restriction>

  </xs:simpleType>

</xs:schema>

 Step 3: Create a new page as "Complex.aspx" & add a label to the form and name it as "lblMsg"

    1. Go to Complex.aspx.cs & define class level global variable a

    private int nErrors = 0;

    private string strErrorMsg = string.Empty;

    public string Errors { get { return strErrorMsg; } }

    1. Go to Pageload event of Comple.aspx page

// IsValidXML return TRUE if no exception, false if any exceptions & respective message is appended to lblMsg

// IsValidXML takes 2 parameters, param1: XML path, param2: XSD path

if (!IsValidXml(@"D:\Surya Prakash\WorkAround\GopalSample\XML\Complex.xml", @"D:\Surya Prakash\WorkAround\GopalSample\XML\Complex.xsd"))
            lblMsg.Text =  Errors;
        else
            lblMsg.Text = string.Format("Success");

    1. IsValidXML function definition

public bool IsValidXml(string xmlPath, string xsdPath)
        {
            bool bStatus = false;
            try
            {
             // Declare local objects
             XmlReaderSettings rs = new XmlReaderSettings();
             rs.ValidationType = ValidationType.Schema;
             rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
        // Event Handler for handling exception & this will be called whenever any mismatch between XML & XSD
            rs.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
                  rs.Schemas.Add(null, XmlReader.Create(xsdPath));
                  // reading xml
                  using (XmlReader xmlValidatingReader = XmlReader.Create(xmlPath, rs))
                 { while (xmlValidatingReader.Read()) { } }
                 
////Exception if error.
                 if (nErrors > 0) { throw new Exception(strErrorMsg);
              }
              else { bStatus = true; }//Success
        }
        catch (Exception error) { bStatus = false; }
        return bStatus;
  }

    1. EventHandler body definition for handling any exception

   void ValidationEventHandler(object sender, ValidationEventArgs e)
   {
        if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: ";
        else strErrorMsg += "ERROR: ";
        nErrors++;
        if (e.Exception.Message.Contains("'Email' element is invalid"))
        {
            strErrorMsg = strErrorMsg + getErrorString("Provided Email data is Invalid", "CAPIEMAIL007") + "\r\n";
        }
        if (e.Exception.Message.Contains("The element 'Person' has invalid child element"))
        {
            strErrorMsg = strErrorMsg + getErrorString("Provided XML contains invalid child element", "CAPINVALID005") + "\r\n";
        }
        else
        {
            strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
        }
    }

  

Step 4: getErrorString: Custom error generation in XML string format

    string getErrorString(string erroString, string errorCode)
    {
        StringBuilder errXMl = new StringBuilder();
        errXMl.Append("<MyError> <errorString> ERROR_STRING </errorString> <errorCode> ERROR_CODE </errorCode> </MyError>");
        errXMl.Replace("ERROR_STRING", erroString);
        errXMl.Replace("ERROR_CODE", errorCode);
        return errXMl.ToString();

    }

Now save the application & run it with below XML. You should be seeing SUCCESS message on the web page.

<Person xmlns:ns0="http://Testing.Message">

  <Name>Surya Prakash</Name>

  <Address>Malkajgiri</Address>

  <Phone>9966537965</Phone>

  <Email>suryaprakasash.bg@gmail.com</Email>

</Person>

So far so good, let modify xml as follow

  1. Add extra tag, which is not defined in XSD. So run the application & look at the exception

Now the xml would look as

<Person xmlns:ns0="http://Testing.Message">

  <Name>Surya Prakash</Name>

  <Address>Malkajgiri</Address>

  <Phone>9966537965</Phone>

    <Email>suryaprakasash.bg@gmail.com</Email>

  <EmpId>123592</EmpId>

</Person>

  1. Provide invalid email in EMAIL tag. So run the application & look at the exception

    Now the XML would look as

<Person xmlns:ns0="http://Testing.Message">

  <Name>Surya Prakash</Name>

  <Address>Malkajgiri</Address>

  <Phone>9966537965</Phone>

  <Email>suryaprakasash.bg@gmail.@.com.com</Email>

</Person>

Hope this helps!

Login to add your contents and source code to this article
Article Extensions
Contents added by Yadlapalli Srikanth on Nov 04, 2011
good
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor