[ Team LiB ] |
Recipe 8.1 Using XSD Schema Files to Load and Save a DataSet StructureProblemYou need to create an XSD schema from a DataSet and define the schema of a DataSet from an XSD schema. SolutionUse the XmlTextWriter and XmlTextReader classes. The sample code contains three event handlers:
The C# code is shown in Example 8-1. Example 8-1. File: XsdSchemaFileForm.cs// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Text; using System.IO; using System.Xml; using System.Xml.Schema; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; private const String ORDERDETAILS_TABLE = "OrderDetails"; // Relation name constants private const String ORDERS_ORDERDETAILS_RELATION = "Orders_OrderDetails_Relation"; // Field name constants private const String ORDERID_FIELD = "OrderID"; // . . . private void writeSchemaButton_Click(object sender, System.EventArgs e) { DataSet ds = new DataSet( ); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable orderTable = new DataTable(ORDERS_TABLE); da.FillSchema(orderTable, SchemaType.Source); da.Fill(orderTable); ds.Tables.Add(orderTable); // Fill the OrderDetails table and add it to the DataSet. da = new SqlDataAdapter("SELECT * FROM [Order Details]", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable orderDetailTable = new DataTable(ORDERDETAILS_TABLE); da.FillSchema(orderDetailTable, SchemaType.Source); da.Fill(orderDetailTable); ds.Tables.Add(orderDetailTable); // Create a relation between the tables. ds.Relations.Add(ORDERS_ORDERDETAILS_RELATION, ds.Tables[ORDERS_TABLE].Columns[ORDERID_FIELD], ds.Tables[ORDERDETAILS_TABLE].Columns[ORDERID_FIELD], true); // Bind the default view of the Orders table to the grid. resultDataGrid.DataSource = ds.Tables[ORDERS_TABLE].DefaultView; // Write the XSD schema to a file. // Display file dialog to select XSD file to write. SaveFileDialog sfd = new SaveFileDialog( ); sfd.InitialDirectory = System.IO.Path.GetTempPath( ); sfd.Filter = "XSD Files (*.xsd)|*.xsd|All files (*.*)|*.*"; sfd.FilterIndex = 1; if (sfd.ShowDialog( ) == DialogResult.OK) { FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write); // Create an XmlTextWriter using the file stream. XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.Unicode); try { // Write the XSD schema to the file. ds.WriteXmlSchema(xtw); resultTextBox.Text="XSD file written."; } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { xtw.Close( ); } } } private void readSchemaButton_Click(object sender, System.EventArgs e) { // Write the XSD schema from a file. // Display file dialog to select XSD file to read. OpenFileDialog ofd = new OpenFileDialog( ); ofd.InitialDirectory = System.IO.Path.GetTempPath( ); ofd.Filter = "XSD Files (*.xsd)|*.xsd|All files (*.*)|*.*"; ofd.FilterIndex = 1; if (ofd.ShowDialog( ) == DialogResult.OK) { FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read); // Create an XmlTextReader using the file stream. XmlTextReader xtr = new XmlTextReader(fs); try { // Read the schema into the DataSet. DataSet ds = new DataSet( ); ds.ReadXmlSchema(xtr); // Bind the default view of the Orders table to the grid. resultDataGrid.DataSource = ds.Tables[ORDERS_TABLE].DefaultView; // Write the XSD schema to a memory stream and // display the XSD schema. MemoryStream ms = new MemoryStream( ); ds.WriteXmlSchema(ms); byte[] result = ms.ToArray( ); ms.Close( ); resultTextBox.Text = Encoding.UTF8.GetString(result, 0, result.Length); } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { xtr.Close( ); } } } private void clearButton_Click(object sender, System.EventArgs e) { // Clear the data grid and the result text box. resultDataGrid.DataSource = null; resultTextBox.Clear( ); } DiscussionThe solution uses the XmlTextWriter and XmlTextReader classes to write and read the XSD schema information. The XmlTextWriter is a writer that provides a fast, non-cached, forward-only way to generate streams or files of XML data. The encoding generated is specified using one of the static property values from System.Text.Encoding described in Table 8-1.
The XmlTextReader provides fast, non-cached, forward-only access to XML data. The XmlTextReader does not validate the XML. For validation, use the XmlValidatingReader class. The XmlTextWriter and XmlTextReader classes conform to the W3C XML 1.0 and the Namespaces in XML recommendations. For more information about the XmlTextWriter and XmlTextReader classes, see the MSDN Library. The WriteXmlSchema( ) and ReadXmlSchema( ) methods of the DataSet class are used to write and read the XSD schema for the XML data. The schema is written using the XSD standard and includes tables, relations, and constraint definitions. Example 8-2 shows the XSD schema written by this solution. Example 8-2. Orders with order details XSD schema<?xml version="1.0" encoding="utf-16"?> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Orders"> <xs:complexType> <xs:sequence> <xs:element name="OrderID" msdata:ReadOnly="true" msdata:AutoIncrement="true" type="xs:int" /> <xs:element name="CustomerID" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="5" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="EmployeeID" type="xs:int" minOccurs="0" /> <xs:element name="OrderDate" type="xs:dateTime" minOccurs="0" /> <xs:element name="RequiredDate" type="xs:dateTime" minOccurs="0" /> <xs:element name="ShippedDate" type="xs:dateTime" minOccurs="0" /> <xs:element name="ShipVia" type="xs:int" minOccurs="0" /> <xs:element name="Freight" type="xs:decimal" minOccurs="0" /> <xs:element name="ShipName" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="40" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="ShipAddress" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="60" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="ShipCity" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="15" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="ShipRegion" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="15" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="ShipPostalCode" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="10" /> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="ShipCountry" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="15" /> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="OrderDetails"> <xs:complexType> <xs:sequence> <xs:element name="OrderID" type="xs:int" /> <xs:element name="ProductID" type="xs:int" /> <xs:element name="UnitPrice" type="xs:decimal" /> <xs:element name="Quantity" type="xs:short" /> <xs:element name="Discount" type="xs:float" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name="Constraint1" msdata:PrimaryKey="true"> <xs:selector xpath=".//Orders" /> <xs:field xpath="OrderID" /> </xs:unique> <xs:unique name="OrderDetails_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true"> <xs:selector xpath=".//OrderDetails" /> <xs:field xpath="OrderID" /> <xs:field xpath="ProductID" /> </xs:unique> <xs:keyref name="Orders_OrderDetails_Relation" refer="Constraint1"> <xs:selector xpath=".//OrderDetails" /> <xs:field xpath="OrderID" /> </xs:keyref> </xs:element> </xs:schema> Use the WriteXml( ) and ReadXml( ) methods of the DataSet to write and read the XML data in addition to the schema information. |
[ Team LiB ] |