13.07.2015 Views

Applied XML Programming for Microsoft .NET.pdf - Csbdu.in

Applied XML Programming for Microsoft .NET.pdf - Csbdu.in

Applied XML Programming for Microsoft .NET.pdf - Csbdu.in

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

XmlTextReader _coreReader = new XmlTextReader(fileName);XmlValidat<strong>in</strong>gReader reader = newXmlValidat<strong>in</strong>gReader(_coreReader);You move around the <strong>in</strong>put document us<strong>in</strong>g the Read method as usual. Actually, youuse the validat<strong>in</strong>g reader as you would any other <strong>XML</strong> .<strong>NET</strong> reader. At each step,however, the structure of the currently visited node is validated aga<strong>in</strong>st the specifiedschema and an exception is raised if an error is found.To validate an entire <strong>XML</strong> document, you simply loop through its contents, as shownhere:private bool ValidateDocument(str<strong>in</strong>g fileName){// Initialize the validat<strong>in</strong>g readerXmlTextReader _coreReader = new XmlTextReader(fileName);XmlValidat<strong>in</strong>gReader reader = newXmlValidat<strong>in</strong>gReader(_coreReader);// Prepare <strong>for</strong> validationreader.ValidationType = ValidationType.Auto;reader.ValidationEventHandler += newValidationEventHandler(MyHandler);// Parse and validate all the nodes <strong>in</strong> the documentwhile(reader.Read()) {}}// Close the readerreader.Close();return true;The ValidationType property is set to the default value—ValidationType.Auto. In thiscase, the reader determ<strong>in</strong>es what type of validation (DTD, XDR, or XSD) is required bylook<strong>in</strong>g at the contents of the file. The caller application is notified of any error through aValidationEventHandler event. In the preced<strong>in</strong>g code, the MyHandler procedure runswhenever a validation error is detected, as shown here:private void MyHandler(object sender, ValidationEventArgs e){// Logs the error that occurredPr<strong>in</strong>tOut(e.Exception.GetType().Name, e.Message);}Figure 3-1 shows the output of the sample program ValidateDocument. The list boxtracks down all the errors that have been detected. The complete code list<strong>in</strong>g <strong>for</strong> thesample application show<strong>in</strong>g how to set up a validat<strong>in</strong>g parser is available <strong>in</strong> this book'ssample files.66

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!