Dom
Dom
Dom
NET
Contents Overview Lesson: Creating XSD Schemas Lesson: Loading Schemas and Data into DataSets Lesson: Writing XML from a DataSet Review Lab 5.1: Working with XML Data in ADO.NET Course Evaluation 1 2 14 25 33 35 43
Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, places or events is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2001-2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Win32, Active Directory, ActiveX, BizTalk, IntelliSense, JScript, MSDN, SQL Server, Visual Basic, Visual C#, Visual C++, Visual J#, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Microsoft ADO.NET uses XML as the format for managing and moving data from a data source to a DataSet object and back. This module explains how to use the XML Schema Definition Language (XSD) to create files that provide structure for working with data in XML documents and DataSets. After completing this module, students will be able to:
! ! ! ! !
Generate an XSD schema from a DataSet by using graphical tools. Save a DataSet structure to an XSD schema file. Create and populate a DataSet from an XSD schema and XML data. Save DataSet data as XML. Write and load changes by using a DiffGram.
Required materials
Microsoft PowerPoint file 2389B_05.ppt Module 5, Reading and Writing XML with ADO.NET Lab 5.1, Working with XML Data in ADO.NET
Preparation tasks
Read all of the materials for this module. Complete the practices and labs. Read the latest .NET Development news at http://msdn.microsoft.com/library/default.asp?url=/nhp/ Default.asp?contentid=28000519
This module contains code examples that are linked to text hyperlinks at the bottom of PowerPoint slides. These examples enable you to teach from code examples that are too long to display on a slide. All of the code examples for this module are contained in one .htm file. Students can copy the code directly from the browser or from the source, and paste it into a development environment. To display a code sample, click a text hyperlink on a slide. Each link opens an instance of Microsoft Internet Explorer and displays the code associated with the link. At the end of each example is a link that displays a table of contents of all examples in this module. After you have finished teaching the code for an example, close the instance of the browser to conserve resources.
Practices
If time constraints occur, one or more practices in this module can be presented as instructor-led demonstrations.
iv
Transition to Practice Exercise: Instruct students to turn to the practice exercise at the end of this topic in the student workbook. The purpose of this practice is to give students experience in using the Visual Studio .NET Schema Editor to create and edit XSD schema documents. Practice Solution: There is no solution for this practice. The purpose of this practice is to show how simple it is to create a valid XSD schema when using Visual Studio designers. After the Practice: What are the advantages of using the Visual Studio .NET graphical tools when creating XSD schema documents?
vi
In the example for loading an XSD schema by using a Stream object, what is the name of the schema file? What exceptions are handled in this example?
Technical Notes: Teach this topic quickly and do not review the code sample. Most of the significant points are covered in the following demonstration. Discussion Questions: Personalize the following questions to the background of the students in your class.
!
How is the ParseSchema procedure programmed to load the DataSet with schema information from PersonPet.xsd? In this demonstration, what DataSet properties and methods are used to retrieve information about tables in the DataSet?
Technical Notes: Discuss each of the XMLReadMode options. Point out that although the auto option is listed, it is poor programming practice to use this rather than specifying a read mode. Also point out that attempts to read data that do not match DataSet schemas will not work. The data will simply not be loaded into the DataSet. No error is generated. Discussion Questions: Personalize the following question to the background of the students in your class. In the example of loading a schema and data into a DataSet, what method is used? What option of the XmlReadMode parameter is used and what does that option do?
vii
What are the differences between using WriteXmlSchema and GetXmlSchema? When would you use WriteXmlSchema and when would you use GetXmlSchema?
Discussion Questions: Personalize the following question to the background of the students in your class. In the example of writing XML data to a file, what would you need to add for this example to also write schema information? The purpose of this demonstration is to show how to save schema and data information from a DataSet. This example loads data into tables and generates an XML data file. Technical Notes: Be prepared to discuss scenarios where DiffGrams are useful. Point out that ADO DiffGrams contain original data in addition to changes.
Demonstration: Writing an Inline Schema and Data to a File Writing DataSet Changes
viii
Identify the purpose and uses of the XmlDataDocument object. Manipulate data in an XmlDataDocument object.
This lesson is optional because students might be unfamiliar with XSD style sheets, XPath queries, and Document Object Model (DOM) node manipulation. If the students have the appropriate XML background, you can choose to present Appendix G at the end of Module 5, Reading and Writing XML with ADO.NET in Course 2389B, Programming with Microsoft ADO.NET. What Is an XmlDataDocument Object? Synchronizing an XmlDataDocument with a DataSet Providing a Hierarchical View of Existing Relational Data Technical Notes: Emphasize that the XMLDataDocument object allows you to manipulate the same data by using relational techniques or XML techniques.
Technical Notes: Point out that you must synchronize a DataSet with an XMLDataDocument object when you create the XMLDataDocument. You cannot set the DataSet property of the XMLDataDocument after creation. This property is read-only. Discussion Questions: Personalize the following questions to the background of the students in your class.
!
What does providing a hierarchical view of existing relational data allow you to do in your applications? What are some examples of XML-related operations that you might want to perform on the data?
Discussion Questions: Personalize the following question to the background of the students in your class. What are some examples of relational operations that you can perform after you provide a relational view of XML data? When would you want to do this?
ix
Technical Notes:
!
This topic is complex. Be prepared to discuss the XSLTransform object and the XMLTextWriter object. Stress that the process and code for applying a style sheet will be almost identical for most cases. It is important for students to recognize the importance of being able to apply a style sheet to relational data. Do not spend more than three minutes explaining the code sample. An alternate way to accomplish this task is to save the XML data to a file and generate a schema to describe the data. It is a simple process to apply a style sheet to the XML file, rather than loading it into an XMLDataDocument object.
Technical Notes: This is a complicated way of querying a DataSet. It is probably better to use the find methods of the dataset or some other query mechanism. This technique is included for completeness. Do not spend more than three minutes explaining the code sample. Discussion Questions: Personalize the following questions to the background of the students in your class.
!
What are some advantages of using XPath queries versus using SQL statements on a DataSet? Are there any situations where you might prefer to use a SQL statement for a query?
2. An XPath query returns results from a Microsoft SQL Server database. How can you load the results into a DataSet? SQL Server generates document fragments rather than well-formed XML documents as the result of sql-xml queries. Use the ReadXml method of the DataSet object with the XmlReadMode parameter set to fragment.
3. Should you create XML files with an inline schema, or generate a separate XSD file? It depends on the situation. If you are shipping data to a client who does not know the structure of the data, it is a good idea to use an inline schema. The inline schema is easy to read or ignore. It is somewhat faster to load data and schemas from a single file rather than from separate files. If you have a choice whether to use separate files or an inline schema, use an inline schema. You might want to use separate files when you have multiple sets of information that conform to the same schema; for example, a standard automobile parts form that always looks the same.
4. You have data stored in a relational database. You want to retrieve this data and filter it by using an Extensible Stylesheet Language for Transformations (XSLT) style sheet before sending it to a client. How can you do this? First, load the data from the database into a DataSet. Next, create an XmlDataDocument object and synchronize it with the DataSet. Use the XmlDataDocument as the information source for an XSLT transformation that uses a style sheet to transform the data. If the data is stored in an XML data file to begin with, you can apply the style sheet in the browser. Because the data is stored relationally in a DataSet, you must first generate a hierarchical representation by loading the information into an XmlDataDocument object before you can transform it.
Overview
! ! !
Creating XSD Schemas Loading Schemas and Data into DataSets Writing XML from a DataSet
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction Microsoft ADO.NET uses XML as the format for managing and moving data from a data source to a DataSet object and back. In addition, you can work directly with data in XML format in an ADO.NET application. This module explains how to use XML Schema Definition Language (XSD) to create files that provide structure for working with data in XML documents and DataSets. After completing this module, you will be able to:
! ! ! ! !
Objectives
Generate an XSD schema from a DataSet by using graphical tools. Save a DataSet structure to an XSD schema file. Create and populate a DataSet from an XSD schema and XML data. Save DataSet data as XML. Write and load changes by using a DiffGram.
What Is an XSD Schema? What Are Typed DataSets? How XSD Schema Information Maps to Relational Structure Generating an XSD Schema with Visual Studio
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction XSD schemas provide the mapping between relational data in DataSets and data in XML documents. XSD schemas define the structure of the data in a DataSet, so that the data can be expressed and used in XML format. After completing this lesson, you will be able to:
! ! ! !
Lesson objectives
Provide a definition of an XSD schema. Give examples of when to use an XSD schema. Create and save an XSD schema by using Microsoft Visual Studio .NET. Create and save an XSD schema by using code.
A representation of relationships between data items A representation of constraints A specification of data types Import data and know the structure of the data Describe the structure of data you export
Practice
Introduction
When you create a new DataSet, no tables or other structures are defined. The structure can be loaded from an XSD schema, or you can create the structure by using code. An XSD schema is a document that describes the structure of an XML document, as well as the constraints on data in that document. An XSD schema can contain the following information:
!
A representation of relationships between data items, similar to the foreign key relationships between tables in a relational database. A representation of constraints similar to the primary key and unique constraints in a relational model. A specification of the data types of each individual element and attribute in an XML document that complies with the XSD schema.
To import data and know the structure of the data that you import. When you receive data in XML format and want to load that data into a DataSet, you can use a schema to define the structure of the data that you are reading.
To describe the structure of data that you are exporting to another consumer. When you want to send data from a DataSet and put it into an XML data document, you can provide a schema to describe the data. In both of these cases, you could infer schema information from the structure of the data in the XML file, rather than using an existing schema. However, you should use a schema when one exists to avoid the added cost of inferring the schema. In addition, the inferred schema might not contain the same level of detail as a complete XSD schema.
<?xml version="1.0" standalone="yes"?> <xsd:schema id="PersonPet" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="PersonPet" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="Person"> <xsd:complexType> <xsd:sequence> <xsd:element name="ID" msdata:AutoIncrement="true" type="xsd:int" /> <xsd:element name="Name" type="xsd:string" minOccurs="0" /> <xsd:element name="Age" type="xsd:int" minOccurs="0" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="Pet"> <xsd:complexType> <xsd:sequence> <xsd:element name="ID" msdata:AutoIncrement="true" type="xsd:int" /> <xsd:element name="OwnerID" type="xsd:int" minOccurs="0" /> <xsd:element name="Name" type="xsd:string" minOccurs="0" /> <xsd:element name="Type" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> <xsd:unique name="Constraint1" msdata:PrimaryKey="true"> <xsd:selector xpath=".//Person" /> <xsd:field xpath="ID" /> </xsd:unique> <xsd:unique name="Pet_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true"> <xsd:selector xpath=".//Pet" /> <xsd:field xpath="ID" /> </xsd:unique> </xsd:element> <xsd:annotation> <xsd:appinfo> <msdata:Relationship name="PersonPet" msdata:parent="Person" msdata:child="Pet" msdata:parentkey="ID" msdata:childkey="OwnerID" /> </xsd:appinfo> </xsd:annotation> </xsd:schema>
The following example shows an XML data document that is based on the schema in the preceding example:
<PersonPet> <Person> <ID>0</ID> <Name>Mark</Name> <Age>18</Age> </Person> <Person> <ID>1</ID> <Name>William</Name> <Age>12</Age> </Person> <Person> <ID>2</ID> <Name>James</Name> <Age>7</Age> </Person> <Person> <ID>3</ID> <Name>Levi</Name> <Age>4</Age> </Person> <Pet> <ID>0</ID> <OwnerID>0</OwnerID> <Name>Frank</Name> <Type>cat</Type> </Pet> <Pet> <ID>1</ID> <OwnerID>1</OwnerID> <Name>Rex</Name> <Type>dog</Type> </Pet> <Pet> <ID>2</ID> <OwnerID>2</OwnerID> <Name>Cottontail</Name> <Type>rabbit</Type> </Pet> <Pet> <ID>3</ID> <OwnerID>3</OwnerID> <Name>Sid</Name> <Type>snake</Type> </Pet> <Pet>
Practice
Create an XML file based on a schema by using the Visual Studio XML Editor.
Save data and its definition for others to consume Validate data in a document Text format, operating-system agnostic
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction In the .NET world, applications communicate by sending XML documents. When you send an XML document to someone, you must send something that describes the structure of the data, data types, relationships, and constraints that are contained in the document. You provide this description by including an XSD schema or an inline schema with your data. Definition Why build a typed DataSet? A typed DataSet is an instance of an existing DataSet class for which schema information has been defined. When you import data from an XML file, you must know how it maps to a relational structure. That information is usually contained in an XSD schema, or in an inline schema with the XML document. You use this schema information to build your DataSet on the client application. When you retrieve data from an XML Web service, database, or XML data document, the typed DataSet on the client is already structured to accept and store the information.
To create a typed DataSet, you must first define a new DataSet class that contains schema information. After defining the class, you create a new instance of the DataSet and populate it with data.
10
ComplexTypes map to tables Nested ComplexTypes map to nested tables Key/Unique constraints map to UniqueConstraints KeyRef elements map to ForeignKeyConstraint
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction <complexType> elements map to tables Nested <complexType> elements map to nested tables <key> and <unique> constraints map to UniqueConstraint <keyref> maps to ForeignKeyConstraint When you use a schema to define your DataSet, certain types of schema tags generate certain relational objects. Within an XSD schema, there is an element called <complexType>. A complexType name usually maps to a table name. A complexType definition can contain elements and attributes, which usually map to column names. A complexType can also contain other complexTypes. In this case, the nested complexType maps to a child table in a parent-child relationship in the relational model. Schemas can contain <key> and <unique> elements, often at the end of the schema. These elements map to primary keys and unique constraints in the relational model. <keyref> elements define the relationships between data items in the schema. <keyref> elements map to foreign key constraints in the relational model.
XSD Schema
11
Example
The following example shows how to use an XSD schema that defines the parts of a relational table named Orders:
<!-- The element name followed by a complexType defines the Orders table --> <xsd:element name="Orders" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="OrderID" type="xsd:int"/> <!--This next block defines the OrderDetails table --> <xsd:element name="OrderDetails" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="ProductID" type="xsd:int"/> <xsd:element name="UnitPrice" type="xsd:number"/> <xsd:element name="Quantity" type="xsd:short"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="OrderDate" type="xsd:dateTime" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="CustomerID" type="xsd:string" use="prohibited" /> </xsd:complexType> <xsd:unique name="Orders_Constraint"> <xsd:selector xpath=".//Orders" /> <xsd:field xpath="OrderID" /> </xsd:unique> <!-- Each OrderID is unique -->
<xsd:key name="OrderDetails_Constraint"> <!-- Primary key --> <xsd:selector xpath=".//OrderDetails" /> <xsd:field xpath="OrderID" /> <xsd:field xpath="ProductID" /> </xsd:key> </xsd:element>
12
Tag completion Color coding Ability to drag and drop standard XSD tags
! !
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction You can use tools in the Visual Studio .NET development environment to create and edit XML schema (XSD) documents. You can also use a simple text editor, such as Microsoft Notepad, to create a schema document. The XML Designer, which contains the Schema Editor, provides the following advantages:
! ! !
Tag completion Color coding Ability to drag and drop standard XSD tags (such as elements, attributes, complex types, simple types, keys, and relations) into an XSD document.
If you have an XML data file and do not have a schema for the data, you can infer an XML schema (XSD) from the data file by following these steps: 1. Add a copy of the XML document into the Solution Explorer, and then view the document. 2. Viewing the document in XML view, right-click the file, and then select Create Schema to add an XSD file to the project.
13
Practice
Create an XML schema (XSD) by using the Visual Studio XML Editor.
10. Add a Country attribute of type String to the Address complex type. Notice that the <BillTo> and <ShipTo> elements are updated to reflect changes in the data type. 11. Switch to the XML view to view the XSD schema. 12. Save PurchaseOrder.xsd, and then quit Visual Studio.
14
Loading a Schema into a DataSet Loading XSD Information from a File Examining Metadata Demonstration: Examining DataSet Structure Loading XML Data into a DataSet
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction Lesson objectives A typed DataSet is one that is based on an XSD schema. In this lesson, you will learn how to create and use typed DataSets. After completing this lesson, you will be able to:
! ! !
Load an XSD schema into a DataSet. Examine metadata. Load data in XML format into a DataSet.
15
To create a relational data structure in the DataSet Use an XSD schema Infer a schema from XML data Manually create the structure of the DataSet by adding code to build tables and create relationships
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Why load an XSD schema into a DataSet? Ways to load a schema into a DataSet You might need to load data from an XML data file into a DataSet object. Before you load the data, you must create a relational data structure in the DataSet. You can load a schema into a DataSet by:
!
Using an XSD schema. When you load an XSD file into a DataSet, the DataSet generates tables, relationships, and constraints based on the data structure described in the XSD schema. This relational representation does not capture all of the detail that is represented by an XSD file, but uses only the information that is required to construct tables, columns, data types, unique constraints, and foreign keys in the relational model. The XSD schema can exist in a separate XSD file, or as an inline schema that precedes the data in an XML data file.
Inferring a schema from XML data. If you have some XML data but no schema, you can generate a schema based on the structure of the XML data. In some cases, the data might be ambiguous or inconsistent. Therefore, if an appropriate schema exists, you should use this schema rather than inferring one from the XML data.
Manually creating the structure of the DataSet by using code to build tables and create relationships.
16
Use ReadXMLSchema to load an existing XSD schema into a DataSet Syntax of ReadXMLSchema
DataSet.ReadXMLSchema (ByVal filename as string | stream as stream | reader as textreader | reader as xmlreader)
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction You use the ReadXmlSchema method of the DataSet object to load an XSD schema into a DataSet. This method is overloaded so that you can you use any of the following to supply the XSD information: a file name, a stream, a TextReader subclass object, or an XmlReader subclass object. The following example shows the syntax for using the ReadXmlSchema method of the DataSet object:
DataSet.ReadXMLSchema (ByVal filename as string | stream as stream | reader as textreader | reader as xmlreader)
The following example shows how to load an XSD schema from a file:
This code loads an XSD schema from a file into a dataset. The XSD schema describes the structure of a purchase order. Private Const PurchaseSchema As String = _ "C:\sampledata\Purchase.xsd" Private myDS as DataSet Private Sub Load_XSD() Try myDS = New DataSet() Console.WriteLine ("Reading the Schema file") myDS.ReadXmlSchema(PurchaseSchema) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
17
The following code loads an XSD schema into a DataSet by using a Stream object. In some applications, you might receive schema information in the form of a stream, from a Web service, or another Internet application.
Private Const PurchaseSchema As String = _ "C:\sampledata\Purchase.xsd" Private myDS as DataSet Private Sub Load_XSD() Dim myStreamReader As StreamReader = Nothing Try myStreamReader = New StreamReader(PurchaseSchema) myDS = New DataSet() Console.WriteLine ("Reading the Schema file") myDS.ReadXmlSchema(myStreamReader) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) Finally If Not myStreamReader Is Nothing Then myStreamReader.Close() End If End Try End Sub
18
Examining Metadata
!
To understand the structure of tables and relationships in the DataSet You can use this information to populate user interface controls and data displays
"
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Why examine DataSet structure? After you have loaded a schema into a DataSet object, or created an instance of a typed DataSet subclass, you can examine the structure of the tables and relationships in the DataSet. The DataSet object contains information such as table names, column names, and data types. You can use this information to populate user interface controls and data displays. How to retrieve DataSet metadata You can use the following properties of the DataSet object to return information about the DataSet structure.
DataSet property Tables Relations What this gives you Allows you to reference the DataTable collection of a DataSet. Allows you to reference the DataRelation collection of a DataSet. Returns the number of tables in a DataSet. Returns the name of a table in the DataTable collection. Allows you to reference the DataColumn collection. Returns the name of a column. Returns the data type of a column. Returns the number of columns in a table.
19
Example
The following example prints out the structure of a DataSet named myDS:
Private Sub DisplayTableStructure() Console.WriteLine("Table structure") 'Print the number of tables Console.WriteLine("Tables count=" & myDS.Tables.Count.ToString()) 'Print the table and column names Dim i, j As Integer For i = 0 To (myDS.Tables.Count - 1) 'Print the table names Console.WriteLine("TableName='" & myDS.Tables(i).TableName & "'.") Console.WriteLine("Columns count=" & myDS.Tables(i).Columns.Count.ToString()) For j = 0 To (myDS.Tables(i).Columns.Count - 1) 'Print the column names and data types Console.WriteLine( vbTab & _ " ColumnName='" & myDS.Tables(i).Columns(j).ColumnName & _ " DataType='" & myDS.Tables(i).Columns(j).DataType.ToString() ) Next Console.WriteLine() Next End Sub
20
Load an XSD schema into a DataSet Use the DataSet properties and methods to retrieve information about tables in the DataSet
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction In this demonstration, you will load an XSD schema into a DataSet. You will then use DataSet properties and methods to retrieve information about the tables in the DataSet. 1. Open <install folder>\DemoCode\Module5\PersonPet.xsd with Notepad and explain how the XSD tags are mapped to relational objects in the DataSet. 2. Open <install folder>\ DemoCode\Module5\ExistingSchema\ExistingSchema.sln with Visual Studio .NET. 3. Double-click the Get Schema button and show the code. 4. Point out that the ParseSchema procedure loads the DataSet myDS with schema information from PersonPet.xsd. 5. Explain the code in the Button1_click procedure. Point out that Tables, Columns, ColumnName, and Count properties are used to return information about the number of tables and the columns in each table. 6. Point out that a set of nested loops is used to reference each column in each table. 7. Run the application and observe the results. 8. Quit Visual Studio .NET.
21
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Loading data and schemas by using the Dataset.ReadXML method You can use the ReadXml method of the DataSet object to load data from an XML file into a DataSet. When you use this method, you can load data from XML files that contain only XML data, or from files that contain XML data as well as an inline schema. An inline schema is an XSD schema that appears at the beginning of the XML data file. This schema describes the XML information that appears after the schema in the XML file. Simplified syntax The ReadXml method is overloaded and can be used to read from a stream object, an XML file, a TextReader subclass object, or an XmlReader subclass object, as shown in the following example:
Dataset.ReadXml(Stream | FileName | TextReader | XmlReader, { ByVal mode as XmlReadMode })
Use the XmlReadMode parameter to specify what the XML file contains and what information should be loaded from the file. This parameter is optional. If no XmlReadMode value is supplied, the default value Auto is used.
22
The following table shows the values for the XmlReadMode parameter of the ReadXml method of the DataSet object.
XmlReadMode value ReadSchema Description Reads any inline schema and then loads the schema and data.
1.
If the DataSet already contains a schema, any new tables that are defined by an inline schema are added to the DataSet. If the inline schema defines a table that is already in the DataSet, an exception is thrown. If the DataSet does not contain a schema, and there is no inline schema, no data is read.
2. 3.
IgnoreSchema
Ignores any inline schema and loads data into the existing DataSet. Any data that does not match the existing schema is discarded. Ignores any inline schema and infers a new schema based on the structure of the XML data. If the DataSet already defines a schema, tables are added to this schema. The data is then loaded into the DataSet. Reads a DiffGram and adds the data to the current schema in the DataSet. Reads XML fragments and appends data to appropriate DataSet tables. This setting is typically used to read XML data generated directly from Microsoft SQL Server. Examines the XML file and chooses the most appropriate option.
1. 2.
InferSchema
DiffGram Fragment
Auto
If the DataSet contains a schema or the XML contains an inline schema, ReadSchema is used. If the DataSet does not contain a schema and the XML does not contain an inline schema, InferSchema is used.
23
The following example first loads a schema into a new DataSet by using the ReadXmlSchema method, and then loads the data from an XML file by using the ReadXml method with the IgnoreSchema option of the XmlReadMode parameter.
Private Const PurchaseSchema As String = _ "C:\sampledata\Purchase.xsd" Private Sub ReadXmlDataOnly() Try myDS = New DataSet() Console.WriteLine("Reading the Schema file") myDS.ReadXmlSchema(PurchaseSchema) Console.WriteLine("Loading the XML data file") myDS.ReadXml("C:\sampledata\PurchaseData.xml", _ XmlReadMode.IgnoreSchema) DataGrid1.DataSource = myDS.Tables(0) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
The following example reads both an inline schema and XML data from an XML file into a DataSet. In this case, PurchaseOrder.xml contains an inline schema in addition to XML data.
Private Sub ReadXmlDataAndSchema() Try myDS = New DataSet() myDS.ReadXml("C:\sampledata\PurchaseOrder.xml", _ XmlReadMode.ReadSchema) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
24
The following example shows how to infer a schema from XML data. In this example, PurchaseOrder.xml contains XML data but no inline schema. When the data is read into a DataSet, the DataSet infers a schema from the structure of the XML data.
Private Sub ReadXmlDataInferSchema() Try myDS = NEW DataSet() myDS.ReadXml("C:\sampledata\PurchaseOrder.xml", _ XmlReadMode.InferSchema) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
25
Writing a Schema to a File, Reader, or Stream Writing DataSet Information to a File or Stream Demonstration: Writing an Inline Schema and Data to a File Writing DataSet Changes
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction Lesson objectives In this lesson, you will learn how to write data in XML format from a DataSet. After completing this lesson, you will be able to:
! ! !
Write a schema to a file, reader, or stream. Write information in a DataSet object to a file or stream. Write DataSet changes.
26
Why write out schema information from a DataSet? Using the WriteXMLSchema method of the DataSet object Using the GetXML method of the DataSet object
"
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Why write out schema information from a DataSet? An application might create and populate a DataSet from several different sources. Therefore, the structure of a DataSet can be fairly complex. If a DataSet is required to run an application in the future, or to allow other applications and services to integrate with XML data, you might want to save the structure and data that is contained in the DataSet to one or more files. By using this strategy, you can easily re-create the structure of the DataSet or construct a new typed DataSet from the XSD file and then load the data when you need it. You can use two different methods of the DataSet object to generate an XSD file:
! !
WriteXmlSchema GetXmlSchema
You can use the WriteXmlSchema method of the DataSet object to save a DataSet schema to an XSD file, stream, or reader object. This method takes a single parameter that specifies the destination of the schema information. The following example shows the syntax for the WriteXmlSchema method of the DataSet object:
WriteXmlSchema (ByVal filename As String | stream As Stream | writer As TextWriter | writer As XmlWriter)
27
Example
This code sample loads a DataSet by using an inline schema and data from an XML file. The schema is then saved to an XSD file by using the WriteXmlSchema method of the DataSet object.
Private Sub SaveXSDSchema() Try myDS = New DataSet() 'Load an inline schema and data from an XML file myDS.ReadXml("C:\sampledata\PurchaseOrder.xml", _ XmlReadMode.ReadSchema) 'Save the schema to an XSD file myDS.WriteXmlSchema("C:\sampledata\POSchema.xsd") Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
To extract schema information from a DataSet and store it as a string, use the GetXmlSchema method of the DataSet object.
Public Function GetXmlSchema() as String
This method has no parameters. Example The following code fragment uses the GetXmlSchema method of the DataSet object to generate a string that contains schema information:
Private Sub XSDSchemaToString() Try Dim StrPurchaseSchema as String myDS = New DataSet() 'Load an inline schema and data from an XML file myDS.ReadXml("C:\sampledata\PurchaseOrder.xml", _ XmlReadMode.ReadSchema) 'Get the schema from the DataSet and load it 'into a string StrPurchaseSchema = myDS.GetXmlSchema() Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
28
Write data and schema information from a DataSet to a file or stream by using the WriteXML method Partial syntax of writing DataSet Information to a file or stream
Overloads Public Sub WriteXml (ByVal filename as String | stream as Stream | writer as XmlWriter | writer as TextWriter, {ByVal mode as XmlWriteMode})
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction Partial syntax You can write data and schema information from a DataSet to a file or stream by using the WriteXml method of the DataSet object. The following example shows partial syntax for the WriteXml method of the DataSet object:
Overloads Public Sub WriteXml (ByVal filename As String | stream As Stream | writer as TextWriter | writer as XmlWriter, {ByVal mode As XmlWriteMode})
XmlWriteMode values
When you use the WriteXml method, you can specify an optional value for the XmlWriteMode parameter. This parameter specifies whether to generate a file that contains only XML data, XML data with an inline XSD schema, or a DiffGram. The following table describes the different values for the XmlWriteMode parameter of the WriteXml method of the DataSet object.
XmlWriteMode value IgnoreSchema What is generated An XML file containing the data from a DataSet. No schema information is included. If the DataSet is empty, no file is created. An XML file containing an inline schema and the data from a populated DataSet. If the DataSet contains only schema information, an inline schema is written to the output file. If the DataSet does not include schema information, no file is created. An XML file in the form of a DiffGram, containing both the original and current values for the data.
WriteSchema
DiffGram
29
The following example saves the data stored in a DataSet as an XML file, but does not write any schema information:
Private Sub SaveXMLDataOnly() Try Dim StrPurchaseSchema as String myDS = New DataSet() 'Load an inline schema and data from an XML file myDS.ReadXml("C:\sampledata\PurchaseOrder.xml", _ XmlReadMode.ReadSchema) 'Save the data portion of the DataSet to a file myDS.WriteXml("C:\sampledata\CurrentOrders.xml", _ XmlWriteMode.IgnoreSchema) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
30
Create a new DataSet object, tables, and columns Populate the DataSet with data Save the contents of the DataSet as an XML file with an inline schema
" "
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction This demonstration shows how to save schema and data information from a DataSet. 1. Start Visual Studio .NET, and open <install folder>\DemoCode\Module5\CreateAndSaveSchema\CreateAndSaveSchem a.sln. 2. View the code for Form1. 3. Examine the code in the LoadDataSet procedure. Point out that this builds a schema by using code rather than by importing an XSD file. Also examine the code that loads data into the tables. 4. Examine the code behind the Create Schema button. Point out the code that generates a schema file. Also point out the code that generates an XML data file. 5. Run the application and examine the output files located in <install folder>\DemoCode\Module5. 6. Close Visual Studio .NET.
31
What is a DiffGram?
"
A file or a stream in XML format that represents changes made to a DataSet Set the WriteXml method of the DataSet object with the XmlWriteMode parameter set to DiffGram.
Creating a DiffGram
"
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Why save DataSet changes? A DataSet is a local information cache. During the lifetime of an application, the data rows in the DataSet are often modified or deleted, and new rows may be added. Although you can send changes in a DataSet back to the database by using an OleDbConnection or SqlConnection object and an OleDbDataAdapter or SqlDataAdapter object, not every application uses a database to store and retrieve information. You might want to store the changes in an XML file. Scenario A salesperson has an application that loads a product stock list from an XML file that he receives in an e-mail message each morning. The application generates a DataSet from this file. During the day, the sales application is not connected to the Internet. At the end of the day, the salesman uses the application to generate an XML document that reflects the changes that he made to the original DataSet, and then sends this file in an e-mail message to the regional sales manager. A DiffGram is an XML format, such as a file or stream, that represents changes made to a DataSet. It contains the original and current data for an element or attribute, and a unique identifier that associates the original and current versions of an element or attribute to each other. A DiffGram is useful when you want to send data across a network and preserve the various versions of the data (Original or Current), in addition to the Row State values (Added, Modified, Deleted, Unchanged) of the DataRows in a DataSet.
Example of DiffGram
Definition of a DiffGram
32
Example of a DiffGram
In the CustomerDataSet, the row with a CustomerID of ALFKI was modified. In the resulting DiffGram, the new version of the row appears at the top of the document and the original version appears inside the <diffgr:before> tag near the end of the document:
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <CustomerDataSet> <Customers diffgr:id="Customers1"msdata:rowOrder="0" diffgr:hasChanges="modified"> <CustomerID>ALFKI</CustomerID> <CompanyName>New Company</CompanyName> </Customers> <Customers diffgr:id="Customers2" msdata:rowOrder="1"> <CustomerID>ANATR</CustomerID> <CompanyName>Ana Trujillo Emparedados y helados</CompanyName> </Customers> </CustomerDataSet> <diffgr:before> <Customers diffgr:id="Customers1" msdata:rowOrder="0"> <CustomerID>ALFKI</CustomerID> <CompanyName>Alfreds Futterkiste</CompanyName> </Customers> </diffgr:before> </diffgr:diffgram>
To generate a DiffGram from a DataSet, set the WriteXml method of the DataSet object with the XmlWriteMode parameter set to DiffGram.
Private Sub SaveDataSetChanges() Try Dim StrPurchaseSchema as String myDS = New DataSet() 'Load an inline schema and data from an XML file myDS.ReadXml("C:\sampledata\Customers.xml", _ XmlReadMode.ReadSchema) 'Make a change to information in the DataSet 'Delete a row myDS.Tables(1).Rows(1).Delete 'Save the data portion of the DataSet as a Diffgram myDS.WriteXml("C:\sampledata\CustomerChanges.xml", _ XmlWriteMode.DiffGram) Catch e as Exception Console.WriteLine("Exception: " & e.ToString()) End Try End Sub
33
Review
! ! !
Creating XSD Schemas Loading Schemas and Data into DataSets Writing XML from a DataSet
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. You want to create an XSD schema from data in an XML document. The document does not contain an inline schema, and no external XSD document exists. What are the ways that you can generate a schema by using Visual Studio .NET? You can create a schema by using the XML Designer. First add the XML file to the project, and then infer a schema by using visual tools.
2. An XPath query returns results from a Microsoft SQL Server database. How can you load the results into a DataSet? SQL Server generates document fragments rather than well-formed XML documents as the result of sql-xml queries. Use the ReadXml method of the DataSet object with the XmlReadMode parameter set to fragment.
34
3. Should you create XML files with an inline schema, or generate a separate XSD file? It depends on the situation. If you are shipping data to a client who does not know the structure of the data, it is a good idea to use an inline schema. The inline schema is easy to read or ignore. It is somewhat faster to load data and schemas from a single file rather than from separate files. If you have a choice whether to use separate files or an inline schema, use an inline schema. You might want to use separate files when you have multiple sets of information that conform to the same schema; for example, a standard automobile parts form that always looks the same.
4. You have data stored in a relational database. You want to retrieve this data and filter it by using an Extensible Stylesheet Language for Transformations (XSLT) style sheet before sending it to a client. How can you do this? First, load the data from the database into a DataSet. Next, create an XmlDataDocument object and synchronize it with the DataSet. Use the XmlDataDocument as the information source for an XSLT transformation that uses a style sheet to transform the data. If the data is stored in an XML data file to begin with, you can apply the style sheet in the browser. Because the data is stored relationally in a DataSet, you must first generate a hierarchical representation by loading the information into an XmlDataDocument object before you can transform it.
35
Exercise 1: Generating a DataSet Schema by Using Visual Studio XML Designer Exercise 2: Creating and Loading a DataSet from XML Exercise 3: Saving DataSet Schemas and Data as XML
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Objectives After completing this lab, you will be able to:
! ! ! !
Create XSD schemas and XML data files by using Visual Studio .NET. Load schemas and data into a DataSet. Write XSD schemas and XML data to a file. Process relational data by using XML techniques.
Prerequisites
Basic knowledge of the structure of an XML document. Basic knowledge of the purpose of an XSD schema.
36
37
8. Save, build, and then run the application. You should see data from customers.xml in the data grid.
38
39
myDS
DataSet Variable
4. Write code to load the XML data into the DataSet by using the information in the following table. (Hint: Use the ReadXml method.)
Parameter File variable XmlReadMode Value myDocument IgnoreSchema
5. Bind the data grid to the Customers table in the DataSet. 6. Save, build, and then run the application. 7. Click the Display Customer Information button. The data grid displays three customers, as defined in Customers.xml.
40
41
2. Add code to the Click event of this button that saves the DataSet schema. Use the information in the following table.
Property File name Value \Program Files\MSDNTrain\2389\Labs\Lab05\ ResultSchema.xsd
3. Save, build, and then run the application. 4. Examine the resulting XSD file to confirm that it reflects the structure of the Customers DataSet.
42
2. Add code to the Click event of this button that saves only the DataSet data. Use the information in the following table.
Property File name Value \Program Files\MSDNTrain\2389\Labs\Lab05\ResultData.xml
3. Save, build, and then run the application. 4. Examine the resulting XML file to confirm that it reflects the data in the Customers DataSet.
2. Save, build, and then run the application. 3. Examine the resulting XML file to confirm that it reflects the data and schema information.
43
Course Evaluation
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Your evaluation of this course will help Microsoft understand the quality of your learning experience. At a convenient time between now and the end of the course, please complete a course evaluation, which is available at http://www.metricsthatmatter.com/survey. Microsoft will keep your evaluation strictly confidential and will use your responses to improve your future learning experience.