XML reader and writer -- application verification when reading XML

Source: Internet
Author: User
Tags xml reader
How to Apply verification when reading XML

This example illustrates how to apply verification when using the xmlvalidatingreader class to read and analyze XML data. Validation is the process of forcibly applying rules to XML content through document type definition (DTD) or a schema. Simply put, the architecture is the XML Representation of DTD, but it can also export the relationship between XML data and type information. The xmlvalidatingreader class provides verification support on xmltextreader.

Note: This example shows how to continue reading the XML topic from a file.

 

VB validationreadingxml. aspx

[Running example] | [View Source Code]

When analyzing documents, xmlvalidatingreader can verify the DTD, XML Schema Definition Language (XSD) architecture, or XML simplified language (XDR) architecture. You can use the validationtype attribute to query the verification options, as shown in the following table.

Verification type Description
Auto This is the default option.
None Verification when analysis is not performed.
DTD Verification Based on DTD.
Schema Verify Based on the XSD architecture.
XDR Verify Based on the XDR architecture.

After you set validationtype to auto, perform the following operations:

  • If no DTD or architecture exists, the XML is analyzed without verification.
  • If <! If the DTD is defined in the doctype...> declaration, the DTD is loaded and the DTD declaration is processed to make the default attributes and regular entities available. They are loaded and analyzed only when regular entities are used (extended.
  • If no <! Doctype...> declaration, but with the XSD "schemalocation" attribute, these XSD schemas are loaded and processed, and all default attributes defined in these schemas are returned.
  • If no <! Doctype...> declare that there is no XSD or XDR architecture information, then this analyzer is not a verification analyzer (that is, validationtype = validationtype. None)
  • If no <! Doctype...> declaration, there is no XSD "schemalocation" attribute, but some namespaces that use the MSXML "X-schema:" Urn prefix will load and process these architectures, return all default attributes defined in these architectures.
  • If no <! Doctype...> declaration, but with <schema> schema declaration, the inline architecture is used for verification.

The sample code (see view source files) Verifies four files. Use books. DTD to verify the first file booksdtd. xml. An error occurred while verifying the second file booksdtdfail. XML with books. DTD. Use the schema. xml file to verify the third file booksschema. xml. Failed to verify the fourth file booksfailschema. XML with the schema. xml file. Schema. XML is an XSD architecture. The sample code uses the DTD or Schema value to set the validationtype attribute to set the required verification type, as shown in the following code.


XmlTextReader myXmlTextReader = new XmlTextReader(document1);            XmlValidatingReader myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader);            myXmlValidatingReader.ValidationType = ValidationType.DTD;            
Dim myXmlTextReader As XmlTextReader = New XmlTextReader(document1)            Dim myXmlValidatingReader As XmlValidatingReader = New XmlValidatingReader(myXmlTextReader)            myXmlValidatingReader.ValidationType = ValidationType.DTD            
C # VB  

The analyzer does not stop because of any type of verification error. It only stops when format error data is found. Since the analyzer does not stop due to verification errors, you can identify all verification errors during an analysis without having to analyze the XML document repeatedly.

As shown in the following code, a verification error causes this example to call the handler method set by the validationeventhandler class before reading the XML document. If this method is not provided, xmlvalidatingreader will throw an xmlschemaexception when the first verification error occurs. In this code example, the success variable indicates the verification status.

The analyzer does not stop because of any type of verification error. It only stops when format error data is found. Since the analyzer does not stop due to verification errors, you can identify all verification errors during an analysis without having to analyze the XML document repeatedly.

private void Validate()            {            try            {            // Set the validation event handler            myXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler (this.ValidationEventHandle);            // Read XML data            while (myXmlValidatingReader.Read()){}            Console.WriteLine ("Validation finished. Validation {0}", (Success==true ? "successful" : "failed"));            }            catch (XmlException e)            {            Console.WriteLine ("XmlException: " + e.ToString());            }            catch (Exception e)            {            Console.WriteLine ("Exception: " + e.ToString());            }            }            public void ValidationEventHandle (object sender, ValidationEventArgs args)            {            Console.Write("\r\n\tValidation error: " + args.Message);            }            
private sub Validate()            try            ' Set the validation event handler            Dim valdel as ValidationEventHandler = new ValidationEventHandler(addressof ValidationEvent)            AddHandler myXmlValidatingReader.ValidationEventHandler, valdel            ' Read XML data            while myXmlValidatingReader.Read()            end While            Dim s as String            if (success = true)            s = "successful"            else            s = "failed"            end if            Console.WriteLine ("Validation finished. Validation {0}", s)            catch e as XmlException            Console.WriteLine ("XmlException: {0} ", e.ToString())            catch e as Exception            Console.WriteLine ("Exception: {0} ", e.ToString())            end try            end sub            public sub ValidationEvent (errorid as object, args as ValidationEventArgs)            Console.Write(Strings.chr(9) & "Validation error: " & args.Message)            end sub            
C # VB  

You can use the callback handler to ensure that the xmlseveritytype enumeration verifies the XML instance document based on the architecture. For all verification errors, there is an xmlseveritytype. error value, which indicates a fatal error. However, there may be no architecture information that can be used to verify elements and attributes. In this case (usually with errorcodes, noelementschemafound, and noattributeschemafound values), the value of xmlseveritytype is xmlseveritytype. Warning.

Summary
  1. Verification can be performed based on the DTD, XSD, or XDR architecture. The required verification type is set by the validation attribute.
  2. Perform verification during read and analysis operations.
  3. The validationeventhandler attribute must be set to receive verification error notifications.
  4. Verification errors do not stop the analysis. Analysis stops only when a format error occurs. This allows you to discover all errors during an analysis.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.