Access and Manipulate XML Data: Transform DataSet data into XML data.
One area in which the .NET Framework's use of XML is especially innovative is in connecting databases with XML. You already know that ADO.NET provides a complete in-memory representation of a relational database through its DataSet object. What the System.Xml namespace adds to this picture is the ability to automatically synchronize a DataSet with an equivalent XML file. In this section of the chapter, you'll learn about the classes and techniques that make this synchronization possible.
The XmlDataDocument Class
The XmlDocument class is useful for working with XML via the DOM, but it's not a data-enabled class. To bring the DataSet class into the picture, you need to use an XmlDataDocument class, which inherits from the XmlDocument class. Table 2.5 shows the additional members that the XmlDataDocument class adds to the XmlDocument class.
Table 2.5. Additional Members of the XmlDataDocument Class
Member | Type | Description |
DataSet | Property | Retrieves a DataSet representing the data in the XmlDataDocument |
GetElementFromRow | Method | Retrieves an XmlElement representing a specified DataRow |
GetRowFromElement | Method | Retrieves a DataRow representing a specified XmlElement |
Load | Method | Loads the XmlDataDocument and synchronizes it with a DataSet |
Synchronizing a DataSet with an XmlDataDocument
The XmlDataDocument class exists to allow you to exploit the connections between XML documents and DataSets. You can do this by synchronizing the XmlDataDocument (and hence the XML document that it represents) with a particular DataSet. You can start the synchronization process with any of these objects:
-
An XmlDataDocument
-
A full DataSet
-
A schema-only DataSet
I'll demonstrate these three options in the remainder of this section.
Starting with an XmlDataDocument
One way to synchronize a DataSet and an XmlDataDocument is to start with the XmlDataDocument and to retrieve the DataSet from its DataSet property. Step By Step 2.4 demonstrates this technique.
STEP BY STEP 2.4 Retrieving a DataSet from an XmlDataDocument -
Add a new form to the project. Name the new form StepByStep2-4.vb. -
Add a Button control named btnLoadXml and a DataGrid control named dgXML to the form. -
Double-click the Button control to open the form's module. Add these lines of code at the top of the module: Imports System.Data Imports System.Xml -
Add code to handle the Button's Click event: Private Sub btnLoadXml_Click(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLoadXml.Click ' Create a new XmlTextReader on the file Dim xtr As XmlTextReader = _ New XmlTextReader("..\Books.xml") ' Create an object to synchronize Dim xdd As XmlDataDocument = New XmlDataDocument() ' Retrieve the associated DataSet Dim ds As DataSet = xdd.DataSet ' Initialize the DataSet by reading the schema ' from the XML document ds.ReadXmlSchema(xtr) ' Reset the XmlTextReader xtr.Close() xtr = New XmlTextReader("..\Books.xml") ' Tell it to ignore whitespace xtr.WhitespaceHandling = WhitespaceHandling.None ' Load the synchronized object xdd.Load(xtr) ' Display the resulting DataSet dgXML.DataSource = ds dgXML.DataMember = "Book" ' Clean up xtr.Close() End Sub -
Set the form as the startup form for the project. -
Run the project. Click the button. The code will load the XML file and then display the corresponding DataSet on the DataGrid control, as shown in Figure 2.4. Figure 2.4. Displaying the DataSet derived from an XmlDataDocument. |
The code in Step By Step 2.4 performs some extra setup to make sure that the DataSet can hold the data from the XmlDataDocument. Even when you're creating the DataSet from the XmlDataDocument, you must still explicitly create the schema of the DataSet before it will contain data. That's because in this technique, you can also use a DataSet that represents only a portion of the XmlDataDocument. In this case, the code takes advantage of the ReadXmlSchema method of the DataSet object to automatically construct a schema that matches the XML document. Because the XmlTextReader object is designed for forward-only use, the code closes and reopens this object after reading the schema so that it can also be used to read the data.
Starting with a Full DataSet
A second way to end up with a DataSet synchronized to an XmlDataDocument is to start with a DataSet. Step By Step 2.5 demonstrates this technique.
EXAM TIP
Automatic Schema Contents When you use the ReadXmlSchema method of the DataSet object to construct an XML schema for the DataSet, both elements and attributes within the XML document become DataColumn objects in the DataSet.
STEP BY STEP 2.5 Creating an XmlDataDocument from a DataSet -
Add a new form to the project. Name the new form StepByStep2-5.vb. -
Add a Button control named btnLoadDataSet and a ListBox control named lbNodes to the form. -
Open Server Explorer. -
Expand the tree under Data Connections to show a SQL Server data connection that points to the Northwind sample database. Expand the Tables node of this database. Drag and drop the Employees table to the form to create a SqlConnection object and a SqlDataAdapter object on the form. -
Select the SqlDataAdapter object. Click the Generate DataSet hyperlink beneath the Properties Window. Name the new DataSet dsEmployees and click OK. -
Add a new module to the project. Name the new module Utility.vb. Alter the code in Utility.vb as follows : Imports System.Xml Module Utility Public Sub XmlToListbox(ByVal xd As XmlDocument, _ ByVal lb As ListBox) ' Get the document root Dim xnodRoot As XmlNode = xd.DocumentElement ' Walk the tree and display it Dim xnodWorking As XmlNode If xnodRoot.HasChildNodes Then xnodWorking = xnodRoot.FirstChild While Not IsNothing(xnodWorking) AddChildren(xnodWorking, lb, 0) xnodWorking = xnodWorking.NextSibling End While End If End Sub Private Sub AddChildren(ByVal xnod As XmlNode, _ ByVal lb As ListBox, ByVal Depth As Integer) ' Add this node to the listbox Dim strNode As String Dim intI As Integer Dim intJ As Integer Dim atts As XmlAttributeCollection ' Only process Text and Element nodes If (xnod.NodeType = XmlNodeType.Element) Or _ (xnod.NodeType = XmlNodeType.Text) Then strNode = "" For intI = 1 To Depth strNode &= " " Next strNode = strNode & xnod.Name & " " strNode &= xnod.NodeType.ToString strNode = strNode & ": " & xnod.Value lb.Items.Add(strNode) ' Now add the attributes, if any atts = xnod.Attributes If Not atts Is Nothing Then For intJ = 0 To atts.Count - 1 strNode = "" For intI = 1 To Depth + 1 strNode &= " " Next strNode = strNode & _ atts(intJ).Name & " " strNode &= _ atts(intJ).NodeType.ToString strNode = strNode & ": " & _ atts(intJ).Value lb.Items.Add(strNode) Next End If ' Recursively walk the children ' of this node Dim xnodworking As XmlNode If xnod.HasChildNodes Then xnodworking = xnod.FirstChild While Not IsNothing(xnodworking) AddChildren(_ xnodworking, lb, Depth + 1) xnodworking = _ xnodworking.NextSibling End While End If End If End Sub End Module -
Double-click the Button control to open the form's module. Add this line of code at the top of the module: Imports System.Xml -
Add code to handle the Button's Click event: Private Sub btnLoadDataSet_Click(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnLoadDataSet.Click ' Fill the DataSet SqlDataAdapter1.Fill(DsEmployees1, "Employees") ' Retrieve the associated document Dim xd As XmlDataDocument = _ New XmlDataDocument(DsEmployees1) ' Display it in the ListBox XmlToListbox(xd, lbNodes) End Sub -
Set the form as the startup form for the project. -
Run the project. Click the button. The code will load the DataSet from the Employees table in the SQL Server database. It will then convert the DataSet to XML and display the results in the ListBox, as shown in Figure 2.5. Figure 2.5. Displaying the XmlDataDocument derived from a DataSet. |
Starting with an XML Schema
The third method to synchronize the two objects is to follow a three-step recipe:
-
Create a new DataSet with the proper schema to match an XML document, but no data.
-
Create the XmlDataDocument from the DataSet
-
Load the XML document into the XmlDataDocument.
Step By Step 2.6 demonstrates this technique.
STEP BY STEP 2.6 Synchronization Starting with a Schema -
Add a new form to the project. Name the new form StepByStep2-6.vb. -
Add a Button control named btnLoadXml , a DataGrid control named dgXML , and a ListBox control named lbNodes to the form. -
Add a new XML Schema file to the project from the Add New Item dialog box. Name the new file Books.xsd . -
Switch to XML view of the schema file and add this code: <?xml version="1.0" encoding="utf-8" ?> <xs:schema id="Books" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Books"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Book"> <xs:complexType> <xs:sequence> <xs:element name="Author" type="xs:string" /> <xs:element name="Title" type="xs:string" /> </xs:sequence> <xs:attribute name="Pages" type="xs:string" /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> -
Double-click the Button control to open the form's module. Add these lines of code at the top of the module: Imports System.Data Imports System.Xml -
Add code to handle the Button's Click event: Private Sub btnLoadXml_Click(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLoadXml.Click ' Create a dataset with the desired schema Dim ds As DataSet = New DataSet() ds.ReadXmlSchema("..\Books.xsd") ' Create a matching document Dim xd As XmlDataDocument = _ New XmlDataDocument(ds) ' Load the XML xd.Load("..\Books.xml") ' Display the XML via the DOM XmlToListbox(xd, lbNodes) ' Display the resulting DataSet dgXML.DataSource = ds dgXML.DataMember = "Book" End Sub -
Set the form as the startup form for the project. -
Run the project. Click the button. The code will load the DataSet and the XmlDataDocument. It will then display the DataSet in the DataGrid and the XML in the ListBox, as shown in Figure 2.6. Figure 2.6. Displaying the XmlDataDocument derived from a DataSet. |
The advantage to using this technique is that you don't have to represent the entire XML document in the DataSet schema; the schema only needs to include the XML elements that you want to work with. For example, in this case the DataSet does not contain the Publisher column, even though the XmlDataDocument includes that column (as you can verify by inspecting the information in the ListBox control).
GUIDED PRACTICE EXERCISE 2.1 As you might guess, the XmlTextReader is not the only class that provides a connection between the DOM and XML documents stored on disk. A corresponding XmlTextWriter class exists that is designed to take an XmlDocument object and write it back to a disk file. For this exercise, you should write a form that allows the user to open an XML file and edit the contents of the XML file on a DataGrid control. When the user is done editing, he should be able to click a button and save the edited file back to disk. You can use the WriteTo method of an XmlDocument or XmlDataDocument object to write that object to disk through an XmlTextWriter. Try this on your own first. If you get stuck or would like to see one possible solution, follow these steps. -
Add a new form named GuidedPracticeExercise2-1 to your Visual Basic .NET project. -
Add two Button controls ( btnLoadXml and btnSaveXml ) and a DataGrid control ( dgXML ) to the form. -
Double-click one of the buttons to open the form's module. Add this code at the top of the module: Imports System.Data Imports System.Xml -
Add this code to handle events from the form: Dim xdd As XmlDataDocument Dim ds As DataSet Private Sub btnLoadXml_Click(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLoadXml.Click Xdd = New XmlDataDocument() ' Create a new XmlTextReader on the file Dim xtr As XmlTextReader = _ New XmlTextReader("..\Books.xml") ' Initialize the DataSet by reading the schema ' from the XML document ds.ReadXmlSchema(xtr) ' Reset the XmlTextReader xtr.Close() xtr = New XmlTextReader("..\Books.xml") ' Tell it to ignore whitespace xtr.WhitespaceHandling = WhitespaceHandling.None ' Load the synchronized object xdd.Load(xtr) ' Display the resulting DataSet dgXML.DataSource = ds dgXML.DataMember = "Book" ' Clean up xtr.Close() End Sub Private Sub GuidedPracticeExercise2_1_Load(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Retrieve the associated DataSet and store it ds = xdd.DataSet End Sub Private Sub btnSaveXml_Click(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSaveXml.Click ' Create a new XmlTextWriter on the file Dim xtw As XmlTextWriter = _ New XmlTextWriter("..\Books.xml", _ System.Text.Encoding.UTF8) ' And write the document to it xdd.WriteTo(xtw) xtw.Close() End Sub -
Set the form as the startup object for the project. -
Run the project. Click the Load XML button to load the Books.xml file to the DataGrid. Change some data on the DataGrid, and then click the Save XML button. Close the form. Open the Books.xml file to see the changed data. The code in this exercise keeps the XmlDataDocument and DataSet variables at the module level so that they remain in scope while the user is editing data. The data is made available for editing by synchronizing a DataSet to an XmlDataDocument and then binding that DataSet to a DataGrid. As the user makes changes on the DataGrid, those changes are automatically saved back to the DataSet, which in turn keeps the XmlDataDocument synchronized to reflect the changes. When the user clicks the Save XML button, the contents of the XmlDataDocument object are written back to disk. |
REVIEW BREAK -
The XmlDataDocument class is a subclass of the XmlDocument class that can be synchronized with a DataSet. -
You can start the synchronization process with the XmlDataDocument or with the DataSet, or you can use a schema file to construct both objects. -
Changes to one synchronized object are automatically reflected in the other. -
You can use an XmlTextWriter object to persist an XmlDocument object back to disk. |