- Sams Teach Yourself XML in 21 Days, Third Edition
- Table of Contents
- About the Author
- Acknowledgments
- We Want to Hear from You!
- Introduction
- Part I: At a Glance
- Day 1. Welcome to XML
- All About Markup Languages
- All About XML
- Looking at XML in a Browser
- Working with XML Data Yourself
- Structuring Your Data
- Creating Well-Formed XML Documents
- Creating Valid XML Documents
- How XML Is Used in the Real World
- Online XML Resources
- Summary
- Q&A
- Workshop
- Day 2. Creating XML Documents
- Choosing an XML Editor
- Using XML Browsers
- Using XML Validators
- Creating XML Documents Piece by Piece
- Creating Prologs
- Creating an XML Declaration
- Creating XML Comments
- Creating Processing Instructions
- Creating Tags and Elements
- Creating CDATA Sections
- Handling Entities
- Summary
- Q&A
- Workshop
- Day 3. Creating Well-Formed XML Documents
- What Makes an XML Document Well-Formed?
- Creating an Example XML Document
- Understanding the Well-Formedness Constraints
- Using XML Namespaces
- Understanding XML Infosets
- Understanding Canonical XML
- Summary
- Q&A
- Workshop
- Day 4. Creating Valid XML Documents: DTDs
- All About DTDs
- Validating a Document by Using a DTD
- Creating Element Content Models
- Commenting a DTD
- Supporting External DTDs
- Handling Namespaces in DTDs
- Summary
- Q&A
- Workshop
- Declaring Attributes in DTDs
- Day 5. Handling Attributes and Entities in DTDs
- Specifying Default Values
- Specifying Attribute Types
- Handling Entities
- Summary
- Q&A
- Workshop
- Day 6. Creating Valid XML Documents: XML Schemas
- Using XML Schema Tools
- Creating XML Schemas
- Dissecting an XML Schema
- The Built-in XML Schema Elements
- Creating Elements and Types
- Specifying a Number of Elements
- Specifying Element Default Values
- Creating Attributes
- Summary
- Q&A
- Workshop
- Day 7. Creating Types in XML Schemas
- Restricting Simple Types by Using XML Schema Facets
- Creating XML Schema Choices
- Using Anonymous Type Definitions
- Declaring Empty Elements
- Declaring Mixed-Content Elements
- Grouping Elements Together
- Grouping Attributes Together
- Declaring all Groups
- Handling Namespaces in Schemas
- Annotating an XML Schema
- Summary
- Q&A
- Workshop
- Part I. In Review
- Well-Formed Documents
- Valid Documents
- Part II: At a Glance
- Day 8. Formatting XML by Using Cascading Style Sheets
- Our Sample XML Document
- Introducing CSS
- Connecting CSS Style Sheets and XML Documents
- Creating Style Sheet Selectors
- Using Inline Styles
- Creating Style Rule Specifications in Style Sheets
- Summary
- Q&A
- Workshop
- Day 9. Formatting XML by Using XSLT
- Introducing XSLT
- Transforming XML by Using XSLT
- Writing XSLT Style Sheets
- Using <xsl:apply-templates>
- Using <xsl:value-of> and <xsl:for-each>
- Matching Nodes by Using the match Attribute
- Working with the select Attribute and XPath
- Using <xsl:copy>
- Using <xsl:if>
- Using <xsl:choose>
- Specifying the Output Document Type
- Summary
- Q&A
- Workshop
- Day 10. Working with XSL Formatting Objects
- Introducing XSL-FO
- Using XSL-FO
- Using XSL Formatting Objects and Properties
- Building an XSL-FO Document
- Handling Inline Formatting
- Formatting Lists
- Formatting Tables
- Summary
- Q&A
- Workshop
- Part II. In Review
- Using CSS
- Using XSLT
- Using XSL-FO
- Part III: At a Glance
- Day 11. Extending HTML with XHTML
- Why XHTML?
- Writing XHTML Documents
- Validating XHTML Documents
- The Basic XHTML Elements
- Organizing Text
- Formatting Text
- Selecting Fonts: <font>
- Comments: <!-->
- Summary
- Q&A
- Workshop
- Day 12. Putting XHTML to Work
- Creating Hyperlinks: <a>
- Linking to Other Documents: <link>
- Handling Images: <img>
- Creating Frame Documents: <frameset>
- Creating Frames: <frame>
- Creating Embedded Style Sheets: <style>
- Formatting Tables: <table>
- Creating Table Rows: <tr>
- Formatting Table Headers: <th>
- Formatting Table Data: <td>
- Extending XHTML
- Summary
- Q&A
- Workshop
- Day 13. Creating Graphics and Multimedia: SVG and SMIL
- Introducing SVG
- Creating an SVG Document
- Creating Rectangles
- Adobe's SVG Viewer
- Using CSS Styles
- Creating Circles
- Creating Ellipses
- Creating Lines
- Creating Polylines
- Creating Polygons
- Creating Text
- Creating Gradients
- Creating Paths
- Creating Text Paths
- Creating Groups and Transformations
- Creating Animation
- Creating Links
- Creating Scripts
- Embedding SVG in HTML
- Introducing SMIL
- Summary
- Q&A
- Workshop
- Day 14. Handling XLinks, XPointers, and XForms
- Introducing XLinks
- Beyond Simple XLinks
- Introducing XPointers
- Introducing XBase
- Introducing XForms
- Summary
- Workshop
- Part III. In Review
- Part IV: At a Glance
- Day 15. Using JavaScript and XML
- Introducing the W3C DOM
- Introducing the DOM Objects
- Working with the XML DOM in JavaScript
- Searching for Elements by Name
- Reading Attribute Values
- Getting All XML Data from a Document
- Validating XML Documents by Using DTDs
- Summary
- Q&A
- Workshop
- Day 16. Using Java and .NET: DOM
- Using Java to Read XML Data
- Finding Elements by Name
- Creating an XML Browser by Using Java
- Navigating Through XML Documents
- Writing XML by Using Java
- Summary
- Q&A
- Workshop
- Day 17. Using Java and .NET: SAX
- An Overview of SAX
- Using SAX
- Using SAX to Find Elements by Name
- Creating an XML Browser by Using Java and SAX
- Navigating Through XML Documents by Using SAX
- Writing XML by Using Java and SAX
- Summary
- Q&A
- Workshop
- Day 18. Working with SOAP and RDF
- Introducing SOAP
- A SOAP Example in .NET
- A SOAP Example in Java
- Introducing RDF
- Summary
- Q&A
- Workshop
- Part IV. In Review
- Part V: At a Glance
- Day 19. Handling XML Data Binding
- Introducing DSOs
- Binding HTML Elements to HTML Data
- Binding HTML Elements to XML Data
- Binding HTML Tables to XML Data
- Accessing Individual Data Fields
- Binding HTML Elements to XML Data by Using the XML DSO
- Binding HTML Tables to XML Data by Using the XML DSO
- Searching XML Data by Using a DSO and JavaScript
- Handling Hierarchical XML Data
- Summary
- Q&A
- Workshop
- Day 20. Working with XML and Databases
- XML, Databases, and ASP
- Storing Databases as XML
- Using XPath with a Database
- Introducing XQuery
- Summary
- Q&A
- Workshop
- Day 21. Handling XML in .NET
- Creating and Editing an XML Document in .NET
- From XML to Databases and Back
- Reading and Writing XML in .NET Code
- Using XML Controls to Display Formatted XML
- Creating XML Web Services
- Summary
- Q&A
- Workshop
- Part V. In Review
- Appendix A. Quiz Answers
- Quiz Answers for Day 1
- Quiz Answers for Day 2
- Quiz Answers for Day 3
- Quiz Answers for Day 4
- Quiz Answers for Day 5
- Quiz Answers for Day 6
- Quiz Answers for Day 7
- Quiz Answers for Day 8
- Quiz Answers for Day 9
- Quiz Answers for Day 10
- Quiz Answers for Day 11
- Quiz Answers for Day 12
- Quiz Answers for Day 13
- Quiz Answers for Day 14
- Quiz Answers for Day 15
- Quiz Answers for Day 16
- Quiz Answers for Day 17
- Quiz Answers for Day 18
- Quiz Answers for Day 19
- Quiz Answers for Day 20
- Quiz Answers for Day 21
Using XPath with a Database
In addition to storing data by using XML, we can also treat databases as XML in .NET in other ways. For example, we can address the data in a dataset by using XPath expressions, and we'll take a look at how this works here in a new Visual Basic .NET project, ch20_04.
Start by creating a new Windows project named ch20_04. In this example, you'll use the XPath expression * to get a node list of all the child elements of the <employee> element. This expression will return all the fields of the various employees in the employee table you worked with in the previous example. To create this example, start by adding to the main form in your project a button with the caption Get Names and two text boxes to display the names, as shown in Figure 20.9. You need to make the text boxes multiline text boxes by setting their Multiline property to true in the properties window at the lower right in the Visual Basic .NET development environment; you need to stretch these boxes as shown in Figure 20.9.
Figure 20.9 Creating the ch20_04 project.
In addition, create a dataset object, DataSet11, that is connected to the employee table in the pubs database, as you did in the previous example. That is, drag an OleDbDataAdapter object to the main form in the project, use the Data Adapter Configuration Wizard to connect this data adapter to the employee table, select Data, Generate Dataset to open the Generate Dataset dialog box, and click OK to create DataSet11.
Now double-click the Get Names button to open the handler method in code that will be called when the button is clicked:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click . . . End Sub
When the Get Names button is clicked, you'll read the data in the dataset—the employee table—into an XmlDataDocument object, which will allow you to address that data by using XPath:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataSet11.Clear() OleDbDataAdapter1.Fill(DataSet11) Dim xmlDoc As New System.Xml.XmlDataDocument(DataSet11) . . . End Sub
Now you have a new XmlDataDocument object, xmlDoc, that holds the employee table, set up explicitly as XML. Table 20.9 lists the significant properties of XmlDataDocument objects, and Table 20.10 lists the significant methods of XmlDataDocument objects.
Table 20.9. Significant Public Properties of XmlDataDocument Objects
Property |
Description |
Attributes |
Returns the attributes of this node. |
BaseURI |
Returns the base URI of the current node. |
ChildNodes |
Returns all the child nodes of the node. |
DataSet |
Returns a dataset that contains the data in the XmlDataDocument object. |
DocumentElement |
Returns the root XmlElement object for the document. |
DocumentType |
Returns the node that contains the DOCTYPE declaration. |
FirstChild |
Returns the first child of the node. |
HasChildNodes |
Returns true if this node has any child nodes. |
InnerText |
Returns or sets the concatenated values of the node and all its child nodes. |
InnerXml |
Returns or sets the markup representing the children of the current node. |
IsReadOnly |
Returns true if the current node is read-only. |
Item |
Returns the given child element. |
LastChild |
Returns the last child of the node. |
LocalName |
Returns the local name of the node. |
Name |
Returns the qualified name of the node. |
NamespaceURI |
Returns the namespace URI of this node. |
NextSibling |
Returns the node immediately following this node. |
NodeType |
Returns the type of the current node. |
OuterXml |
Returns the markup representing this node and all its child nodes. |
OwnerDocument |
Returns the XmlDocument object to which the current node belongs. |
ParentNode |
Returns the parent of this node (for nodes that can have parents). |
Prefix |
Returns or sets the namespace prefix of this node. |
PreserveWhitespace |
Returns or sets a value indicating whether to preserve whitespace. |
PreviousSibling |
Returns the node immediately preceding this node. |
Value |
Returns or sets the value of the node. |
Table 20.10. Significant Public Methods of XmlDataDocument Objects
Method |
Description |
AppendChild |
Adds the given node to the end of the list of child nodes of the current node. |
CreateAttribute |
Creates an XmlAttribute object with the given name. |
CreateCDataSection |
Creates an XmlCDataSection object that contains the given data. |
CreateComment |
Creates an XmlComment object that contains the given data. |
CreateDocumentFragment |
Creates an XmlDocumentFragment object. |
CreateDocumentType |
Returns a new XmlDocumentType object. |
CreateElement |
Creates an XmlElement object. |
CreateNode |
Creates an XmlNode object. |
CreateProcessingInstruction |
Creates an XmlProcessingInstruction object with the given name and data. |
CreateSignificantWhitespace |
Creates an XmlSignificantWhitespace node. |
CreateTextNode |
Creates an XmlText object with the given text. |
CreateWhitespace |
Creates an XmlWhitespace node. |
CreateXmlDeclaration |
Creates an XmlDeclaration node with the given values. |
Equals |
Determines whether two object instances are equal. |
GetElementById |
Returns the XmlElement object that has the given ID. |
GetElementFromRow |
Retrieves the XmlElement object associated with the given DataRow object. |
GetElementsByTagName |
Returns an XmlNodeList object that contains a list of all descendant elements that match the given name. |
GetRowFromElement |
Retrieves the DataRow object associated with the given XmlElement object. |
GetType |
Returns the type of the current instance. |
ImportNode |
Imports a node from another document to the current document. |
InsertAfter |
Inserts the given node immediately after the given reference node. |
InsertBefore |
Inserts the given node immediately before the given reference node. |
Load |
Loads the XmlDataDocument object by using the given data source. |
LoadXml |
Loads the XML document from the given string. |
PrependChild |
Adds the given node to the beginning of the list of child nodes for this node. |
RemoveAll |
Removes all the child nodes and/or attributes of the current node. |
RemoveChild |
Removes the given child node. |
ReplaceChild |
Replaces the child node oldChild with the newChild node. |
Save |
Saves the XML document to the given location. |
SelectNodes |
Selects a list of nodes that match the XPath expression. |
SelectSingleNode |
Selects the first XmlNode object that matches the XPath expression. |
WriteTo |
Saves the XmlDocument object. |
A XmlDataDocument object has a DocumentElement property that returns the document object of its XML documents as an XmlElement object. This XmlElement object supports a method called SelectNodes that lets us select XML nodes by using XPath expressions. To select all the employee elements in the employee table, all you have to do is pass the SelectNodes method the XPath expression *, and you get back a NodeList object back that holds the matching nodes:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataSet11.Clear() OleDbDataAdapter1.Fill(DataSet11) Dim xmlDoc As New System.Xml.XmlDataDocument(DataSet11) Dim nodeList As System.Xml.XmlNodeList = xmlDoc.DocumentElement.SelectNodes("*") . . . End Sub
Now you have a node list of the <employee> elements, extracted from your XmlDataDocument using XPath. How can you access the data in the corresponding employee records in the dataset? You can do that with the XmlDataDocument object's GetRowFromElement method—all you have to do is to pass an XML element to this method, and it'll return the dataset row containing the employee's record. When you have the employee's data record, you can extract the employee's first and last names (Fields 1 and 3 in each record) this way:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataSet11.Clear() OleDbDataAdapter1.Fill(DataSet11) Dim xmlDoc As New System.Xml.XmlDataDocument(DataSet11) Dim nodeList As System.Xml.XmlNodeList = xmlDoc.DocumentElement.SelectNodes("*") Dim tempRow As DataRow Dim tempNode As System.Xml.XmlNode For Each tempNode In nodeList tempRow = xmlDoc.GetRowFromElement(CType(tempNode, System.Xml.XmlElement) ) If Not tempRow Is Nothing Then TextBox1.Text += tempRow(1).ToString() + ControlChars.CrLf If Not tempRow Is Nothing Then TextBox2.Text += tempRow(3).ToString() + ControlChars.CrLf Next End Sub
When you run this example and click the Get Names button, you get all the employees records by using XPath, and then look up all the employees' first and last names and display them as shown in Figure 20.10.
Figure 20.10 Running the ch20_04 project.
Today you've used XPath to access records in a dataset, thanks to the XmlDataDocument object. Listing 20.3 shows the code that we've written for this example. Although in this example we used only the simple XPath expression * to access all the employees in the employee table, we can use full XPath expressions as well.
Example 20.3. Button-Handling Code in the ch20_04 Project (from Form1.vb in the ch20_04 Project)
Public Class Form1 Inherits System.Windows.Forms.Form . . . Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click DataSet11.Clear() OleDbDataAdapter1.Fill(DataSet11) Dim xmlDoc As New System.Xml.XmlDataDocument(DataSet11) Dim nodeList As System.Xml.XmlNodeList = _ xmlDoc.DocumentElement.SelectNodes("*") Dim tempRow As DataRow Dim tempNode As System.Xml.XmlNode For Each tempNode In nodeList tempRow = xmlDoc.GetRowFromElement(CType(tempNode, _ System.Xml.XmlElement)) If Not tempRow Is Nothing Then TextBox1.Text += _ tempRow(1).ToString() + ControlChars.CrLf If Not tempRow Is Nothing Then TextBox2.Text += _ tempRow(3).ToString() + ControlChars.CrLf Next End Sub End Class
Using XPath is one way to address data in databases. However, XPath isn't powerful enough to handle databases, which is why the W3C is introducing XQuery—which is described in the next section.