programming4us
programming4us
WEBSITE

ASP.NET 4 in VB 2010 : XML Validation (part 2) - Validating an XML Document

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019

3. Validating an XML Document

The following example shows you how to validate an XML document against a schema, using an XmlReader that has validation features built in.

The first step when performing validation is to import the System.Xml.Schema namespace, which contains types such as XmlSchema and XmlSchemaCollection:

Imports System.Xml.Schema

You must perform two steps to create the validating reader. First, you create an XmlReaderSettings object that specifically indicates you want to perform validation. You do this by setting the ValidationType property and loading your XSD schema file into the Schemas collection, as shown here:

' Configure the reader to use validation.
Dim settings As New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema

' Create the path for the schema file.
Dim schemaFile As String = Path.Combine(Request.PhysicalApplicationPath, _
  "App_Data\SuperProProductList.xsd")

' Indicate that elements in the namespace
' http://www.SuperProProducts.com/SuperProProductList should be
' validated using the schema file.
settings.Schemas.Add("http://www.SuperProProducts.com/SuperProProductList", _
  schemaFile)

					  

Second, you need to create the validating reader using the shared XmlReader.Create() method. This method has several overloads, but the version used here requires a FileStream (with the XML document) and the XmlReaderSettings object that has your validation settings:

' Open the XML file.
Dim fs As New FileStream(file, FileMode.Open)

' Create the validating reader.
Dim r As XmlReader = XmlReader.Create(fs, settings)

The XmlReader in this example works in the same way as the XmlTextReader you've been using up until now, but it adds the ability to verify that the XML document follows the schema rules. This reader throws an exception (or raises an event) to indicate errors as you move through the XML file.

The following example shows how you can create a validating reader that uses the SuperProProductList.xsd file to verify that the XML in SuperProProductList.xml is valid:

' Set the validation settings.
Dim settings As New XmlReaderSettings()
settings.Schemas.Add("http://www.SuperProProducts.com/SuperProProductList", _
  schemaFile)
settings.ValidationType = ValidationType.Schema

' Open the XML file.
Dim fs As New FileStream(file, FileMode.Open)

' Create the validating reader.
Dim r As XmlReader = XmlReader.Create(fs, settings)

' Read through the document.
Do While r.Read()
    ' Process document here.
    ' If an error is found, an exception will be thrown.
Loop
fs.Close()

					  

Using the current file, this code will succeed, and you'll be able to access each node in the document. However, consider what happens if you make the minor modification shown here:

<Product ID="A" Name="Chair">

Now when you try to validate the document, an XmlSchemaException (from the System.Xml.Schema namespace) will be thrown, alerting you to the invalid data type, as shown in Figure 1.

Figure 1. An XmlSchemaException

Instead of catching errors, you can react to the XmlReaderSettings.ValidationEventHandler event. If you react to this event, you'll be provided with information about the error, but no exception will be thrown. To connect an event handler to this event, you can attach an event handler before you create the XmlReader:

// Connect to the method named ValidateHandler.
AddHandler settings.ValidationEventHandler, AddressOf ValidateHandler

The event handler receives a ValidationEventArgs object as a parameter, which contains the exception, a message, and a number representing the severity:

Private Sub ValidateHandler(ByVal sender As Object, _
  ByVal e As ValidationEventArgs)
    lblStatus.Text &= "Error: " & e.Message & "<br />"
End Sub

To test the validation, you can use the XmlValidation.aspx page in the online samples. It allows you to validate a valid SuperProProductList, as well as two other versions, one with incorrect data and one with an incorrect element (see Figure 2).

Figure 2. The validation test page

Because all XmlReader objects process XML one line at a time, this validation approach performs the best and uses the least amount of memory. But if you already have an XDocument in memory, you can validate it in a similar way using the XDocument.Validate() method.

Other  
 
Top 10
Free Mobile And Desktop Apps For Accessing Restricted Websites
MASERATI QUATTROPORTE; DIESEL : Lure of Italian limos
TOYOTA CAMRY 2; 2.5 : Camry now more comely
KIA SORENTO 2.2CRDi : Fuel-sipping slugger
How To Setup, Password Protect & Encrypt Wireless Internet Connection
Emulate And Run iPad Apps On Windows, Mac OS X & Linux With iPadian
Backup & Restore Game Progress From Any Game With SaveGameProgress
Generate A Facebook Timeline Cover Using A Free App
New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
- Messages forwarded by Outlook rule go nowhere
- Create and Deploy Windows 7 Image
- How do I check to see if my exchange 2003 is an open relay? (not using a open relay tester tool online, but on the console)
- Creating and using an unencrypted cookie in ASP.NET
- Directories
- Poor Performance on Sharepoint 2010 Server
- SBS 2008 ~ The e-mail alias already exists...
- Public to Private IP - DNS Changes
- Send Email from Winform application
- How to create a .mdb file from ms sql server database.......
programming4us programming4us
programming4us
 
 
programming4us