Contents Overview 1 Lesson: Introduction to Querying XML Using XPath 2 Lesson: Creating and Navigating a Document Cache 9 Lesson: Executing Your Query 17 Review 33 Lab 5.1: Querying XML Documents Using XPath 35 Module 5: Querying XML 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, place or event 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. ©2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, Win32, Active Directory, ActiveX, BizTalk, IntelliSense, JScript, Microsoft Press, MSDN, SQL Server, Visual Basic, Visual C#, and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. Module 5: Querying XML iii Instructor Notes This module explains the process of querying an Extensible Markup Language (XML) document by using the XML Path Language (XPath). It explains how to write code to load an XML document and how to create a navigation cursor by using an XPathNavigator object. It also explains how to create your query by using an XPathDocument object and how to examine the result types. In addition, this module describes how to compile your query and evaluate your results. After completing this module, students will be able to: Describe the business reasons for querying Extensible Markup Language (XML) documents by using the XML Path Language (XPath). Cache XML data for querying by using an XPathDocument object. Create an XPathNavigator object to navigate through an XML document. Compile and evaluate the result of an XPathExpression object. Iterate through an XmlNodeList object returned by an XPath expression. To teach this module, you need the following materials: Microsoft ® PowerPoint ® file 2663A_05.ppt 2663A_05_code.htm Module 5, “Querying XML” Instructor-led demonstration file To prepare for this module: Read all of the materials for this module. Complete the lab. Practice the instructor-led demonstration and code examination. The demonstrations in this module consist of a demonstration and code walkthrough of querying an XML document. To prepare for these demonstrations, perform the demonstration steps as they are written and prepare to explain how the code works. In this module some of the PowerPoint slides provide hyperlinks that open a code samples page in the Web browser. The code samples page provides a way to show and discuss code samples when there is not enough space for the code on the PowerPoint slide. It also allows students to copy code samples directly from the browser window and paste them into a development environment. All of the linked code samples for this module are in a single .htm file. To open a code sample, click the appropriate hyperlink on the slide. To navigate between code samples in a particular language, use the table of contents provided at the top of the code page. Each hyperlink opens a separate instance the Web browser, so it is a good practice to click Back in Internet Explorer after you view a code sample. This will close the browser window and return you to the PowerPoint presentation. Presentation: 60 minutes Lab: 60 minutes Required materials Preparation tasks Hyperlinked Code Examples iv Module 5: Querying XML How to Teach This Module This section contains information that will help you to teach this module. Lesson: Introduction to Querying XML Using XPath This section describes the instructional methods for teaching each topic in this lesson. This lesson introduces XPath and the reasons for using it. To understand the rest of the module, the students must understand how XPath expressions are a navigational language for XML documents. Stress that XPath is an XML language that provides access to nodes and their contents, wherever the nodes are located in an XML document. The role of the World Wide Web Consortium (W3C) in the development of XPath in conjunction with the development of XQuery illustrates the dynamic nature of XML technologies and languages. Stress that this evolution is ongoing and requires continual adjustments and refinements by both vendors and developers. However, stress that the development is not random. This topic introduces students to the steps in the query process. Emphasize that these steps are general. For example, students might compile the query or they might not. Explain that this information is covered in the third lesson of this module. In this demonstration, you will load a product catalog document and demonstrate multiple queries. These queries have different return types, including node sets, numbers, strings, and Boolean values. Lesson: Creating and Navigating a Document Cache This section describes the instructional methods for teaching each topic in this lesson. This topic explains why to use an XPathDocument object to cache data. Emphasize that using the XPathDocument object provides a way for students to query data in a read-only manner. This topic also explains how to preserve all white space in the source XML document. Explain how XmlSpace.Preserve and XmlSpace.Default function. To navigate through an XML source document, students must create a cursor by creating an XPathNavigator object. In this topic, students will learn how to use the CreateNavigator() method to create an XPathNavigator object. This topic defines five methods that students can use to position the navigator by traversing the XML document. Why Query XML Using XPath? What Is the Query Process? Demonstration: Querying XML Using XPath What Is an XPathDocument Object? How to Create a Navigato r How to Navigate Nodes in an XPathDocument Module 5: Querying XML v Lesson: Executing Your Query This section describes the instructional methods for teaching each topic in this lesson. In this topic, students will learn how to create and compile a query by using the Compile() method. Emphasize that one advantage of compiling a query is that doing so allows you to determine the data type of the information returned by the query. This topic explains how to use the Evaluate() method to evaluate number return types. Emphasize that the Evaluate() method returns a typed result. This topic explains how to use the Select() methods to evaluate node return types. Explain that students can either compile the query into an XPathExpression object and then use the Select() method of the XPathNavigator object, or they can execute a string XPath expression directly by using one of the Select() methods of the XPathNavigator object. Students might have noticed in the Select() method example in the previous topic that the resulting nodes are stored in an XPathNodeIterator. This topic explains how to use an XPathNodeIterator to iterate through a node set. Emphasize that students must call the MoveNext() method to move the XPathNodeIterator to the first node in the selected set. Explain the code underlying the application that you demonstrated at the beginning of this module. Review There are several multiple-choice review questions at the end of the chapter. Review these questions with your students before proceeding to the lab. The review questions are mostly based on conceptual understanding and procedures that were covered thoroughly in the module. You can use a discussion format to answer the questions so that every student gets the benefit of knowing the right answers. 1. If the students are not sure what method to call to move the XPathNodeIterator to the first node in the selected set, review the third lesson. 2. If students have difficulty with this question, review XmlSpace members, especially the default and the preserve members. 3. If students answer that you cannot execute a query directly without compiling it, correct this perception. At the same time, emphasize the benefits of compiling queries. 4. This question explores the distinctions between the Evaluate() and Select() methods. How to Create and Compile a Query How to Execute XPath Expressions That Return Numbers How to Execute XPath Expressions That Return Node Sets How to Iterate Through a Node Set Code Examination vi Module 5: Querying XML Lab 5.1: Querying XML Documents Using XPath Before beginning this lab, students should have completed the module and answered the review questions. Students will need to be able to perform most of the tasks that they learned in the lessons. Customization Information This section identifies the lab setup requirements for a module and the configuration changes that occur on student computers during the labs. This information is provided to assist you in replicating or customizing Microsoft Official Curriculum (MOC) courseware. Lab Setup There are no lab setup requirements that affect replication or customization. Lab Results There are no configuration changes on student computers that affect replication or customization. Module 5: Querying XML 1 Overview Introduction to Querying XML Using XPath Creating and Navigating a Document Cache Executing Your Query ***************************** ILLEGAL FOR NON - TRAINER USE ****************************** This module explains the process of querying an Extensible Markup Language (XML) document by using the XML Path Language (XPath). It explains how to write code to load an XML document and how to create a navigation cursor by using an XPathNavigator object. It also explains how to create your query by using an XPathDocument object and how to examine the result types. In addition, this module describes how to compile your query and evaluate your results. Because an XPath expression can return a set of nodes, you will learn how to iterate through a set of nodes by using an XPathNodeIterator object. After completing this module, you will be able to: Describe the business reasons for querying XML documents by using XPath. Cache XML data for querying by using an XPathDocument object. Create an XPathNavigator object to navigate through an XML document. Compile and evaluate the result of an XPathExpression object. Iterate through an XmlNodeList object returned by an XPath expression. Introduction Objectives 2 Module 5: Querying XML Lesson: Introduction to Querying XML Using XPath Why Query XML Using XPath? What Is the Query Process? Demonstration: Querying XML Using XPath ***************************** ILLEGAL FOR NON - TRAINER USE ****************************** In this lesson, you will gain an understanding of XPath and how you can use XPath to locate parts of XML documents and navigate through a document that is represented as a tree of nodes. After completing this lesson, you will be able to: Describe the business reasons for querying XML documents by using XPath. Describe the steps in the querying process. Introduction Lesson ob jectives Module 5: Querying XML 3 Why Query XML Using XPath? You can use XPath to: Search Filter Summarize XPath : XML :: Transact-SQL : SQL Server Transact-SQL provides a standard language for manipulating relational database objects XPath provides a standard language for navigating an XML document as a hierarchical tree of nodes ***************************** ILLEGAL FOR NON - TRAINER USE ****************************** XPath is a programming language developed by the World Wide Web Consortium (W3C) specifically to address the nodes of an XML source. XPath is also well suited to querying an XML source. You can use XPath to extract from an XML source whatever pattern of content or XML structure you require. Some of the functionality of XPath is similar to the functionality of the Document Object Model (DOM). For example, by using the DOM, you can locate a certain piece of XML data by node type. However, the use of XPath to specify location information in an XML document is far more pervasive than the use of the DOM. What then is XPath, and why is it the technology of choice for querying XML? XPath was developed in part to correct some of the limitations inherent in querying XML by using the DOM. XPath code that addresses and navigates through nodes is much simpler than similar code written for the DOM. XPath allows you to navigate through the nodes of an XML source. You can also combine XPath navigation with other programming techniques. For example, you can use XPath to locate parts of an XML document to generate results for a query with XQuery and XML Views in Microsoft ® SQL Server ™ 2000. Introduction Wh y use XPath? 4 Module 5: Querying XML The following table illustrates how you can use XPath. Example Action Microsoft .NET Framework objects used Get all the <ProductName> elements in a document with a price attribute value > $12.95. Search An XPathDocument object is optimized for query. Use an XPath expression to locate nodes. Change price information in an XML product catalog. Locate information to modify An XmlDocument object provides an implementation of the W3C DOM. Use an XPath expression to locate nodes to be modified. Only find what matches a specified search criterion. Filter You can apply an Extensible Stylesheet Language for Transformation (XSLT) style sheet to an XPathDocument object. The XSLT style sheet often contains an XPath expression. Get a count of the number of parts that are out of stock. Summarize You can query an XPathDocument object to provide a count or sum of information in the document, by using an XPath expression. Examples of using XPath [...]... stream, file, TextReader, or XmlReader Module 5: Querying XML Example 11 The following example illustrates how to create a new XPathDocument object: // C# XPathDocument doc = new XPathDocument("C:\CatalogFile .xml" ); 'Visual Basic Dim doc As XPathDocument = New _ XPathDocument("C:\CatalogFile .xml" ) Preserving white space You can optionally specify to preserve the white space of the XML source in the XPathDocument... is a file or an XmlReader The optional parameter XmlSpace can have the following values Value XmlSpace.Default Preserve only the significant white space XmlSpace.Preserve Preserve all white space XmlSpace.None Example Description Do not preserve white space The following example illustrates how to preserve all white space in the source XML document: // C# //Create an XmlTextReader XmlTextReader CatalogReader;... XPathDocument doc = new XPathDocument(CatalogReader, XmlSpace.Preserve); 'Visual Basic 'Create an XmlTextReader Dim CatalogReader As XmlTextReader 'Code to populate the reader from a file… '…etc… 'Create and populate the XPathDocument, preserving all white 'space Dim doc As XPathDocument = New _ XPathDocument(CatalogReader,XmlSpace.Preserve) 12 Module 5: Querying XML How to Create a Navigator Create an XPathNavigator... USE****************************** Introduction Querying by using XPath provides a way for your application to navigate from one node to the next, and to perform various operations along the way Querying an XML document To query an XML document, you generally perform the following steps: 1 Write code to load an XML document into an appropriate cache You can use an XmlDocument object, XPathDocument object, DataSet, or XmlDataDocument,... type double Module 5: Querying XML Example of evaluating a numerical result 23 The following example illustrates how to evaluate a numerical result: // C# using using using using using System; System.IO; System .Xml; System .Xml. XPath; System.Windows.Forms; public class Sample { public static void Main() { //Create and populate the document XPathDocument doc = new XPathDocument("Order .xml" ); //Create... price: " + total); } } Code continued on the following page 24 Module 5: Querying XML 'Visual Imports Imports Imports Imports Imports Basic System System.IO System .Xml System .Xml. XPath System.Windows.Forms Public Class Sample Public Shared Sub Main() 'Create and populate the document Dim doc As XPathDocument = New XPathDocument("Order .xml" ) 'Create the navigator Dim nav As XPathNavigator = doc.CreateNavigator()... query an XML document, you must load the XML document and create a navigator by creating an XPathNavigator object Lesson objectives After completing this lesson, you will be able to: Load an XML document into an XPathDocument object Create a navigator by creating an XPathNavigator object Navigate an XPathDocument by using XPathNavigator methods 10 Module 5: Querying XML What Is an XPathDocument Object?... execution 5 Evaluate the results Depending on the type of information returned, you can process results by iterating through a set of nodes, or simply process the values returned 6 Module 5: Querying XML Demonstration: Querying XML Using XPath Load document XPathDocument Load document XPathDocument Create navigator XPathNavigator Create navigator XPathNavigator Create query XPathExpression Create query... application Module 5: Querying XML 9 Lesson: Creating and Navigating a Document Cache What Is an XPathDocument Object? How to Create a Navigator How to Navigate Nodes in an XPath Document *****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction In this lesson, you will gain an understanding of how to prepare to query an XML document To query an XML document,... If End If End Sub Module 5: Querying XML 17 Lesson: Executing Your Query How to Create and Compile a Query How to Execute XPath Expressions That Return Numbers How to Execute XPath Expressions That Return Node Sets How to Iterate Through a Node Set Code Examination *****************************ILLEGAL FOR NON-TRAINER USE****************************** Introduction After you load the XML document you . owners. Module 5: Querying XML iii Instructor Notes This module explains the process of querying an Extensible Markup Language (XML) document by using the XML. 2 Module 5: Querying XML Lesson: Introduction to Querying XML Using XPath Why Query XML Using XPath? What Is the Query Process? Demonstration: Querying