Sunday, March 27, 2011

Validate XML aganist an XSD in Asp.Net C#




Please visit my new Web Site https://coderstechzone.com



Most of the times when we are working with XML we need to validate the XML file from an XSD file. Here i am showing an code example how one can validate XML file using an XSD in Asp.Net C#.

To do that add an aspx page in your project.











Now under Page_Load event write the below code:
using System;
using System.Xml;
using System.Text;
using System.Xml.Schema;

public partial class Validate_XML_XSD : System.Web.UI.Page
{
    private StringBuilder sB = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string xmlPath = MapPath("MenuXML.xml");
            string xsdPath = MapPath("MenuXML.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);
    }  
}

Hope now you can validate XML file easily.

1 comments:

Unknown said...

I get an error when I run your code
I copied and pasted it:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1513: } expected

Source Error:


Line 4: using System.Xml;
Line 5: using System.Text;
Line 6: using System.Xml.Schema;
Line 7:
Line 8: public partial class Validate_XML_XSD : System.Web.UI.Page

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash