(Optional) Schema Validation with Class XmlReader

Recall from Section 19.6 that schemas provide a means for specifying XML document structure and validating XML documents. Such validation helps an application determine whether a particular document it receives is complete, ordered properly and not missing any data. In Section 19.6, we used an online XSD schema validator to verify that an XML document conforms to an XML Schema. In this section, we show how to perform the same type of validation programmatically using classes provided by the .NET Framework.

Validating an XML Document Programmatically

Class XmlReader can validate an XML document as it reads and parses the document. In this example, we demonstrate how to activate such validation. The program in Fig. 19.28 validates an XML document that the user chooseseither book.xml (Fig. 19.11) or fail.xml (Fig. 19.29)against the XML Schema document book.xsd (Fig. 19.12).

Figure 19.28. Schema-validation example.

(This item is displayed on pages 978 - 979 in the print version)

 1 // Fig. 19.28: ValidationTest.cs
 2 // Validating XML documents against schemas.
 3 using System;
 4 using System.Windows.Forms;
 5 using System.Xml;
 6 using System.Xml.Schema; // contains XmlSchemaSet class
 7
 8 namespace ValidationTest
 9 {
10 public partial class ValidationTestForm : Form
11 {
12 public ValidationTestForm()
13 {
14 InitializeComponent();
15 } // end constructor
16
17 private XmlSchemaSet schemas; // schemas to validate against
18 private bool valid = true; // validation result
19
20 // handle validateButton Click event
21 private void validateButton_Click( object sender, EventArgs e )
22 {
23 schemas = new XmlSchemaSet(); // create the XmlSchemaSet class
24
25 // add the schema to the collection
26 schemas.Add( "http://www.deitel.com/booklist", "book.xsd" );
27
28 // set the validation settings 
29 XmlReaderSettings settings = new XmlReaderSettings();
30 settings.ValidationType = ValidationType.Schema; 
31 settings.Schemas = schemas; 
32 settings.ValidationEventHandler += ValidationError; 
33
34 // create the XmlReader object
35 XmlReader reader = 
36  XmlReader.Create( filesComboBox.Text, settings );
37
38 // parse the file
39 while ( reader.Read() ); // empty body
40
41 if ( valid ) // check validation result
42 {
43 consoleLabel.Text = "Document is valid";
44 } // end if
45
46 valid = true; // reset variable
47 reader.Close(); // close reader stream
48 } // end method validateButton_Click
49 50 // event handler for validation error 51 private void ValidationError( object sender , 52 ValidationEventArgs arguments ) 53 { 54 lblConsole.Text = arguments.Message; 55 valid = false; // validation failed 56 } // end method ValidationError 57 } // end class ValidatorTestForm 58 } // end namespace ValidatorTest

Figure 19.29. XML file that does not conform to the XML Schema document in Fig. 19.12.

(This item is displayed on pages 979 - 980 in the print version)

 1  = "1.0"?>
 2 
 3 
 4
 5  = "http://www.deitel.com/booklist">
 6 
 7 
Visual Basic 2005 How to Program, 3/e 8 9 10 11 Visual C# 2005 How to Program 12 13 14 15 Java How to Program, 6/e 16 17 18 19 C++ How to Program, 5/e 20 Internet and World Wide Web How to Program, 3/e 21 22 23 24 XML How to Program 25 26

Line 17 creates XmlSchemaSet variable schemas. An object of class XmlSchemaSet stores a collection of schemas against which an XmlReader can validate. Line 23 assigns a new XmlSchemaSet object to variable schemas, and line 26 calls this object's Add method to add a schema to the collection. Method Add receives as arguments a namespace URI that identifies the schema (http://www.deitel.com/booklist) and the name and location of the schema file (book.xsd in the current directory).

Lines 2932 create and set the properties of an XmlReaderSettings object. Line 30 sets the XmlReaderSettings object's ValidationType property to the value ValidationType.Schema, indicating that we want the XmlReader to perform validation with a schema as it reads an XML document. Line 31 sets the XmlReaderSettings object's Schemas property to schemas. This property sets the schema(s) used to validate the document read by the XmlReader.

Line 32 registers method ValidationError with the settings object's ValidationEventHandler. Method ValidationError (lines 5256) is called if the document being read is found to be invalid or an error occurs (e.g., the document cannot be found). Failure to register a method with ValidationEventHandler causes an exception (XmlException) to be thrown when the XML document is found to be invalid or missing.

After setting the ValidationType property, Schemas property and ValidationEventHandler of the XmlReaderSettings object, we are ready to create a validating XmlReader. Lines 3536 create an XmlReader that reads the file selected by the user from the cboFiles ComboBox and validates it against the book.xsd schema.

Validation is performed node-by-node by calling method Read of the XmlReader object (line 39). Because we set XmlReaderSettings property ValidationType to ValidationType.Schema, each call to Read validates the next node in the document. The loop terminates either when all the nodes have been validated or when a node fails validation.

Detecting an Invalid XML Document

The program in Fig. 19.28 validates the XML document book.xml (Fig. 19.12) against the book.xsd (Fig. 19.11) schema successfully. However, when the user selects the XML document of Fig. 19.29, validation failsthe book element in lines 1821 contains more than one title element. When the program encounters the invalid node, method ValidationError (lines 5156 of Fig. 19.28) is called, which displays a message explaining why validation failed.

Preface

Index

    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look

    Arrays

    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2

    Multithreading

    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures

    Generics

    Collections

    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types

    Index



    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Flylib.com © 2008-2020.
    If you may any questions please contact us: flylib@qtcs.net