1. Trang chủ
  2. » Công Nghệ Thông Tin

Module 5: Reading and Writing XML with ADO.NET

54 1,4K 8
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Module 5: Reading and Writing XML with ADO.NET
Trường học Microsoft Corporation
Chuyên ngành ADO.NET
Thể loại module
Năm xuất bản 2001-2002
Thành phố Redmond
Định dạng
Số trang 54
Dung lượng 0,97 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Transition to Practice Exercise: In this practice, you will create an XML file based on a schema by using the Microsoft Visual Studio® XML Editor.. The purpose of this practice is to gi

Trang 1

Module 5: Reading and Writing XML with

ADO.NET

Contents

Overview 1

Lesson: Creating XSD Schemas 2

Lesson: Loading Schemas and Data into

Trang 2

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

Trang 3

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

To teach this module, you need the following 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

To prepare for this module:

! 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

If time constraints occur, one or more practices in this module can be presented

Trang 4

How to Teach This Module

This section contains information that will help you to teach this module

Lesson: Creating XSD Schemas

This section describes the instructional methods for teaching each topic in this lesson

Technical Notes: The example of PersonPet.xsd was chosen because the

structure closely resembles two tables in a relational database and can be easily understood by students who have experience with relational databases A more typical representation of this data would contain child information for pets as a nested complex type inside the Person elements Spend only a few minutes explaining the code sample A more typical example is given later in the module

Transition to Practice Exercise: In this practice, you will create an XML file

based on a schema by using the Microsoft Visual Studio® XML Editor

Instruct students to turn to the practice exercise at the end of this topic in the student workbook Guide the students through the practice

Practice Solution: There is no solution provided The purpose of the exercise

is to give students experience in using the XML Designer to create an XML file

After the Practice:

• When would you use an XSD schema, and when would you create the DataSet structure programmatically?

Technical Notes: This section defines a typed DataSet as one that inherits

tables and relationships from another DataSet class Be prepared to discuss the uses for an abstract base class if students are not familiar with object-oriented programming techniques

Discussion Questions: Personalize the following question to the background of the students in your class

• What are the advantages of using typed DataSets?

Technical Notes: The code sample in this section represents a typical

hierarchical document The purpose is to identify structures that will translate to relational tables and objects Walk through this example to help students

understand what happens when the ReadXML method is used to infer a

Trang 5

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?

Generating an XSD

Schema with Visual

Studio

Trang 6

Lesson: Loading Schemas and Data into DataSets

This section describes the instructional methods for teaching each topic in this lesson

Discussion Questions: Personalize the following question to the background of the students in your class

• What are the advantages and disadvantages of the three different ways to load a schema into a DataSet?

Discussion Questions: Personalize the following questions to the background

of the students in your class

! 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?

Loading a Schema into a

Trang 7

Lesson: Writing XML from a DataSet

This section describes the instructional methods for teaching each topic in this lesson

Discussion Questions: Personalize the following questions to the background

of the students in your class

! 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

Trang 8

Appendix G: Using the XmlDataDocument Object

This optional, teachable appendix introduces the XMLDataDocument object

In general, this object is useful for treating relational data as if it were XML

data You typically use the XMLDataDocument object to apply XML

techniques such as filtering with a style sheet or an XML Path Language (XPath) query

After completing this lesson, students will be able to:

! 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

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?

Trang 9

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

Trang 10

Review: Reading and Writing XML with ADO.NET

This section provides the answers to review questions at the end of this module

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

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

Trang 11

Overview

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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:

! 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

Introduction

Objectives

Trang 12

Lesson: Creating XSD Schemas

Structure

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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:

! 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

Introduction

Lesson objectives

Trang 13

What Is an XSD Schema?

" 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

XSD Example XML Document Example

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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

There are two basic reasons to use XSD schemas:

! 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

Trang 14

The following example shows a two-level XSD schema:

<xsd:element name="Name" type="xsd:string" minOccurs="0" />

<xsd:element name="Type" type="xsd:string" minOccurs="0" />

<msdata:Relationship name="PersonPet" msdata:parent="Person"

msdata:child="Pet" msdata:parentkey="ID" msdata:childkey="OwnerID" />

Trang 15

The following example shows an XML data document that is based on the schema in the preceding example:

Trang 16

<ID>4</ID>

<OwnerID>3</OwnerID> <Name>Tickles</Name> <Type>spider</Type> </Pet>

<Pet>

<ID>5</ID>

<OwnerID>1</OwnerID> <Name>Tweetie</Name> <Type>canary</Type> </Pet>

</PersonPet>

Trang 17

Create an XML file based on a schema by using the Visual Studio XML Editor

! Create an XML file based on a target schema

1 Start Visual Studio NET and create a new Microsoft Visual Basic® or Microsoft Visual C#™ Empty Project

2 On the File menu, click Add Existing Item Add install folder\Practices\Mod05\PhoneList.xsd to the project Double-click the file

in the Solution Explorer to open an editor window The editor opens by default in DataSet view, showing a graphical representation of the schema for the DataSet

3 Switch to the XML view and examine the schema Note that a <customers> element has three child elements and one attribute

4 On the File menu, click Add New Item Add a new XML file named PhoneList.xml to the project

5 Right-click the new XML document, and then click Properties

6 Change the Target Schema to http://tempuri.org/PhoneList.xsd, and then click OK Notice that Visual Studio automatically adds a schema reference

and a parent tag to the XML document

! Add data to the XML document

1 Type a < symbol between the <CustomerData> tags Visual Studio suggests

an appropriate XML element based on the target schema Press the TAB key

to insert the <customers> element into the XML document

2 Type a space Visual Studio suggests an XML attribute based on the target

schema Press the TAB key to insert the ContactName attribute into the

5 Between the <customers> and </customers> tags, type a < symbol Visual

Studio suggests appropriate child elements based on the target schema Double-click the suggested tag to insert a <CompanyName> child element into the XML document

6 Type a > symbol to add a closing tag for the <CompanyName> element

Add data for the company name

7 Use the Visual Studio XML Editor to complete the information for this customer

8 Save the changes

9 Switch the XML Editor to Data view and type the name of another customer

10 Switch the XML Editor to XML view Notice that the tags and data are entered for you

Practice

Trang 18

What Are Typed DataSets?

" Save data and its definition for others to consume

" Validate data in a document

" Text format, operating-system agnostic

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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

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

Introduction

Definition

Why build a typed

DataSet?

Trang 19

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

! To create a typed DataSet

1 Create or obtain an XSD schema that describes the data that you expect to retrieve You use an XSD schema to define tables, columns, data types, constraints, and relationships in a DataSet This schema could also be inferred from the structure of data in an XML file

2 Generate a new DataSet based on that schema information When you use Visual Studio NET, the development environment generates a class to describe the DataSet The name that you give to the DataSet is the name of the class

3 Create a new instance of the DataSet class When you create a new DataSet based on this class, you create a typed DataSet that inherits the tables, columns, and other structure from the parent class

4 Populate the DataSet instance with data

Generating a typed

DataSet class

Trang 20

How XSD Schema Information Maps to Relational Structure

How XSD information maps to relational structure

" ComplexTypes map to tables

" Nested ComplexTypes map to nested tables

" Key/Unique constraints map to UniqueConstraints

" KeyRef elements map to ForeignKeyConstraint

XSD Schema

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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

Trang 21

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"/>

Trang 22

Generating an XSD Schema with Visual Studio NET

" Tag completion

" Color coding

" Ability to drag and drop standard XSD tags

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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:

2 Viewing the document in XML view, right-click the file, and then select

Create Schema to add an XSD file to the project

Trang 23

Create an XML schema (XSD) by using the Visual Studio XML Editor

! Create a new XML schema

1 Start Visual Studio NET, and then create a new Empty Project

2 On the File menu, click Add New Item Add a new XML Schema named PurchaseOrder.xsd to the project

3 Drag a new element from the Toolbox onto the designer surface Change the

element name to PurchaseOrder

4 Drag a complexType to the designer surface Change the complexType

name to Address

5 In the Address complexType, click the first cell on the first row, and then click element in the drop-down list This is a child element

6 In the second cell on the first row, where you enter the name of the child

element, type Name

7 In the third cell on the first row, where you choose the data type of the child

element, choose string

8 Add the following three additional child elements to the Address complex

type

City String Street String Zip Integer

9 Add the following child elements to the <PurchaseOrder> element

BillTo Address ShipTo Address

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

Practice

Trang 24

Lesson: Loading Schemas and Data into DataSets

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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

Introduction

Lesson objectives

Trang 25

Loading a Schema into a DataSet

" 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 ******************************

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

Why load an XSD

schema into a DataSet?

Ways to load a schema

into a DataSet

Trang 26

Loading XSD Information from a File

into a DataSet

DataSet.ReadXMLSchema (ByVal filename as string | stream as stream | reader as textreader | reader as xmlreader)

Visual Basic Example Visual Basic Example

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

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

Trang 27

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

Example of loading an

XSD schema by using a

Stream object

Ngày đăng: 26/10/2013, 23:15

TỪ KHÓA LIÊN QUAN