Generating and Using XSD Schemas

Team-Fly    

Developing XML Web Services and Server Components with Visual C#™ .NET and the .NET Framework, Exam Cram™ 2 (Exam 70-320)
By Amit Kalani, Priti Kalani

Table of Contents
Chapter 3.  Accessing and Manipulating XML Data


In Chapter 2, "Consuming and Manipulating DataSets," you learned how to create an XSD schema in the Visual Studio .NET user interface by dragging and dropping XML elements from the toolbox. This method is useful when you need to create a schema from scratch. But sometimes, you want to create a schema to match an existing object.

Generating an XSD Schema

One obvious source for an XML Schema is an XML file. An XML file can contain explicit schema information (in the form of an embedded schema), or it can contain implicit schema information in its structure. Here's a sample file, Products.xml, that contains embedded schema information:

 <?xml version="1.0" encoding="UTF-8"?> <root xmlns:xsd="http://www.w3.org/2001/XMLSchema"   xmlns:od="urn:schemas-microsoft-com:officedata"> <xsd:schema>  <xsd:element name="dataroot">   <xsd:complexType>    <xsd:choice maxOccurs="unbounded">     <xsd:element ref="Products"/>    </xsd:choice>   </xsd:complexType>  </xsd:element>  <xsd:element name="Products">   <xsd:annotation>    <xsd:appinfo/>   </xsd:annotation>   <xsd:complexType>    <xsd:sequence>      <xsd:element name="ProductID"         od:jetType="autonumber"         od:sqlSType="int" od:autoUnique="yes"         od:nonNullable="yes">       <xsd:simpleType>        <xsd:restriction base="xsd:integer"/>       </xsd:simpleType>      </xsd:element>      <xsd:element name="ProductName" minOccurs="0"          od:jetType="text" od:sqlSType="nvarchar">       <xsd:simpleType>        <xsd:restriction base="xsd:string">         <xsd:maxLength value="40"/>        </xsd:restriction>       </xsd:simpleType>      </xsd:element>     </xsd:sequence>    </xsd:complexType>   </xsd:element> </xsd:schema> <dataroot xmlns:xsi= "http://www.w3.org/2000/10/XMLSchema-instance">   <Products>     <ProductID>1</ProductID>     <ProductName>Chai</ProductName>   </Products> </dataroot> </root> 

If the file contains explicit schema information, you can use the DataSet object to read that information and create the corresponding schema as a separate file, as shown here:

 // Load the XML file with inline schema info XmlTextReader xtr = new XmlTextReader(@"..\..\Products.xml"); // Read the schema (only) into a DataSet DataSet ds = new DataSet(); ds.ReadXmlSchema(xtr); // Write the schema out as a separate stream StringWriter sw = new StringWriter(); ds.WriteXmlSchema(sw); txtSchema.Text = sw.ToString(); 

The DataSet object must have the capability to read an XML Schema so that it can construct a matching data structure in memory. The .NET Framework designers thoughtfully exposed this capability to you through the ReadXmlSchema() and WriteXmlSchema() methods of the DataSet object. But what if the file does not contain explicit schema information? It turns out that you can still use the DataSet object because this object also can infer an XML Schema based on the data in an XML file. For example, here's how to use the DataSet object to infer a schema for the Books.xml file:

 // Load an XML file with no schema information XmlTextReader xtr = new XmlTextReader(@"..\..\Books.xml"); // Read the schema (only) into a DataSet DataSet ds = new DataSet(); String[] ns = {}; ds.InferXmlSchema(xtr, ns); // Write the schema out as a separate stream StringWriter sw = new StringWriter(); ds.WriteXmlSchema(sw); txtSchema.Text = sw.ToString(); 

You have at least four ways to obtain XSD files for your applications:

  • You can use a file generated by an external application such as Microsoft SQL Server or Microsoft Access.

  • You can create your own schema files from scratch, using the techniques that you learned in Chapter 2.

  • You can extract inline schema information from an XML file by using the DataSet.ReadXmlSchema() method.

  • You can infer schema information from an XML file by using the DataSet.InferXmlSchema() method.

Using an XSD Schema

The prime use of a schema file is to validate the corresponding XML file. Although any XML file that conforms to the syntactical rules for XML is well formed, this does not automatically make the file valid. A valid XML file is one whose structure conforms to a specification. This specification can be in the form of an XML Schema or a Document Type Description (DTD), for example. Any valid XML file is well formed, but not every well-formed XML file is valid. The .NET Framework provides good support for validating XML files.

To validate an XML document, you can use the XmlValidatingReader class. This class implements the XmlReader class and provides support for validating XML documents. It can also validate the XML document as it is read in to the XmlDocument object. To use the XmlValidatingReader object to validate an XML document with an inline schema, you should supply a handler for any validation errors, as in this code sample:

 private void btnValidate_Click(object sender, System.EventArgs e) {     // Load a document with an inline schema     XmlTextReader xtr = new XmlTextReader(@"..\..\Products.xml");     // Prepare to validate it     XmlValidatingReader xvr = new XmlValidatingReader(xtr);     xvr.ValidationType = ValidationType.Schema;     // Tell the validator what to do with errors     xvr.ValidationEventHandler +=         new ValidationEventHandler(ValidationHandler);     // Load the document, thus validating     XmlDocument xd = new XmlDocument();     xd.Load(xvr);     // Clean up     xvr.Close(); } public void ValidationHandler(object sender, ValidationEventArgs e) {     // Dump any validation errors to the UI     txtErrors.AppendText(e.Message + "\n"); } 

An inline schema cannot contain an entry for the root element of the document, so even when the document is otherwise valid, you'll get an error from that node. As you can see, the XmlValidatingReader object is constructed so that it does not stop on validation errors. Instead, it continues processing the file, but it raises an event for each error. This lets your code decide how to handle errors while still filling the XmlDocument object.

You can also validate an XML file against an external schema. To do this, you can load the schema and the XML file separately and tell the XmlValidatingReader class to compare one to the other, as shown in the following code sample:

 private void btnValidate_Click(object sender, System.EventArgs e) {     // Load a document with an external schema     XmlTextReader xtr = new XmlTextReader(@"..\..\Books2.xml");     // Prepare to validate it     XmlValidatingReader xvr = new XmlValidatingReader(xtr);     xvr.ValidationType = ValidationType.Schema;     // Tell the validator what to do with errors     xvr.ValidationEventHandler +=         new ValidationEventHandler(ValidationHandler);     // Load the schema     XmlSchemaCollection xsc = new XmlSchemaCollection();     xsc.Add("xsdBooks", @"..\..\Books2.xsd");     // Tell the validator which schema to use     xvr.Schemas.Add(xsc);     // Load the document, thus validating     XmlDocument xd = new XmlDocument();     xd.Load(xvr);     // Clean up     xvr.Close(); } public void ValidationHandler(object sender, ValidationEventArgs e) {     // Dump any validation errors to the UI     txtErrors.AppendText(e.Message + "\n"); } 

    Team-Fly    
    Top


    MCAD Developing XML Web Services and Server Components with Visual C#. NET and the. NET Framework Exam Cram 2 (Exam Cram 70-320)
    Managing Globally with Information Technology
    ISBN: 789728974
    EAN: 2147483647
    Year: 2002
    Pages: 179

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