About Me

My photo
Hello, I'm a technology geek looking to upgrade my programming skills. These are some of the things I'm learning along my journey.

Thursday, August 16, 2012

Exchanging Data Between XML and SQL Server With Validation

This post is a continuation of "Exchanging Data Between XML and SQL Server". Here we will add data validation before the data is written to the XML file.

The first thing to do is let Visual Studio generate an XSD (schema) file for you. Double-click on the "books.xml" file in the "Solution Explorer" and click on "XML" at the top menu. Select "Create Schema".


Once the "books.xsd" file has been created, right-click on the "books.xsd" tab and select "Save books.xsd" and choose the current location the "books.xml" is located.


Once this is done, the code to read the XSD file can be done before the XML is processed.


Example
 //*******************test schema******************
 try
    {
      XmlDocument xmld = new XmlDocument();
      xmld.Load(@"C:\Users\ken\Documents\Visual Studio 2010\Projects\XMLtoDatabaseWithValidation\XMLtoDatabaseWithValidation\books.xml");
      xmld.Schemas.Add(null, @"C:\Users\ken\Documents\Visual Studio 2010\Projects\XMLtoDatabaseWithValidation\XMLtoDatabaseWithValidation\books.xsd");
      xmld.Validate(ValidationCallBack);
    }
catch (Exception ex)
    {
      Console.WriteLine("Caught a problem: " + ex.Message);
    }
//******************end test schema***************

private void ValidationCallBack(object sender, ValidationEventArgs e)
{
   Console.WriteLine("There is a problem with the schema or xml document: " + "\n" + e.Message);
            
   throw new Exception();
}


Once this is done, you can try running the XML with no problems and then introduce errors in either the XSD file or XML file to see what happens.

Click ((here)) for the project code.

No comments:

Post a Comment