Using ADO.NET and XML Together


So far in this chapter, you've seen how to work with XML documents. In this section, you'll now learn how to work with XML documents with the help of ADO.NET. There are two approaches to work with XML and ADO.NET. Using the first approach, you can directly read XML documents by using a DataSet's methods. Not only can you read XML documents in a DataSet, you can also update and save XML documents by using a DataSet. Besides the DataSet object, which is defined in the System.Data namespace, the System.Xml namespace defines classes that can integrate ADO.NET components with XML. In this section, you'll see both of these approaches.

Reading XML Using a DataSet

In ADO.NET, you can access the data using the DataSet class. The DataSet class implements methods and properties to work with XML documents.

Using the ReadXML Method

ReadXml is an overloaded method; you can use it to read a data stream, TextReader, XmlReader, or an XML file and to store data in a DataSet object, which can later be used to display the data in a tabular format. The ReadXml method has eight overloaded forms that can accept the Stream, String, TextReader, XmlReader types of objects as the first parameter; the second argument is of type XmlReadMode.

The XmlReadMode parameter defines the read mode with these objects. The read mode is of type XmlReadMode. XmlReadMode specifies how to read XML data and a relational schema into a DataSet. Table 6-5 describes the XmlReadMode members.

Table 6-5: The XmlReadMode Members

MEMBER

DESCRIPTION

Auto

This is the default mode. It automatically sets the best-suited mode. For example, If the data is a DiffGram, it sets XmlReadMode to DiffGram. If the DataSet already has a schema, or the document contains an inline schema, it sets XmlReadMode to ReadSchema. If the DataSet doesn't already have a schema and the document does not contain an inline schema, it sets XmlReadMode to InferSchema.

DiffGram

Reads a DiffGram.

Fragment

Reads an XML fragment.

IgnoreSchema

Ignores any inline schema. If any data doesn't match the existing schema, it's discarded.

InferSchema

If the DataSet already contains a schema, the current schema is extended by adding new tables or adding columns to existing tables.

ReadSchema

Reads an XML schema.

Note

See Chapter 3 and Chapter 4 for more details about the DataSet object.

In the following example, create a new DataSet object and call the DataSet.ReadXml method to load the books.xml file in a DataSet object:

 ' Create a DataSet Object Dim ds As DataSet = New DataSet() ' Fill with the data ds.ReadXml("books.xml ") 

Once you have a DataSet object, you know how powerful it is. Make sure you provide the correct path to books.xml.

Note

Make sure you add a reference to System.Data and the System.Data.Common namespace before using DataSet and other common data components.

Using the ReadXmlSchema Method

The ReadXmlSchema method reads an XML schema in a DataSet object. It has four overloaded forms. You can use a TextReader, string, stream, and XmlReader. The following example shows how to use a file as direct input and call the ReadXmlSchema method to read the file:

 Dim ds As DataSet = New DataSet() ds.ReadXmlSchema("c:\\books.xml") 

The following example reads the file XmlTextReader and uses XmlTextReader as the input of ReadXmlSchema:

 ' Create a dataset object Dim ds As DataSet = New DataSet("New DataSet") ' Read xsl in an XmlTextReader Dim myXmlReader As XmlTextReader = New XmlTextReader("c:\\books.xml") ' Call ReadXmlSchema ds.ReadXmlSchema(myXmlReader) myXmlReader.Close() 

Writing XML Using a DataSet

Not only for reading, the DataSet class contains methods to write XML files from a DataSet object and fill the data to the file.

Using the WriteXml Method

The WriteXml method writes the current data (the schema and data) of a DataSet object to an XML file. By using this method, you can write data to a file, stream, TextWriter, or XmlWriter. The WriteXml method takes an argument of type Stream, String, TextWriter, or XmlWriter.

When writing XML using WriteXml , you can also specify the write mode. The second parameter of WriteXml is a type of XmlWriteMode, which specifies the write mode. XmlWriteMode specifies how to write XML data and a relational schema from a DataSet. Table 6-6 describes the XmlWriteMode members.

Table 6-6: The XmlWriteMode Members

MEMBER

DESCRIPTION

DiffGram

Writes a DataSet's contents including original and current values as a DiffGram.

IgnoreSchema

Writes the current contents of a DataSet as XML data, without an XSD schema. If there's no data in a DataSet, nothing is written.

WriteSchema

This is the default mode. The method writes the current contents as XML data with the relational structure as inline XSD schema. If the DataSet has only a schema with no data, only the inline schema is written. If there's no data in a DataSet, nothing is written.

Listing 6-20 creates a DataSet, fills the data for the DataSet, and writes the data to an XML file using the WriteXml method.

Listing 6-20: Using the WriteXml Method

start example
 Imports System.Data Imports System.Xml Imports System.IO Module Module1   Sub Main()     try     ' Create a DataSet, namespace and Student table     'with Name and Address columns     Dim ds As DataSet = New DataSet("DS")     ds.Namespace = "StdNamespace"     Dim stdTable As DataTable = New DataTable("Student")     Dim col1 As DataColumn = New DataColumn("Name")     Dim col2 As DataColumn = New DataColumn("Address")     stdTable.Columns.Add(col1)     stdTable.Columns.Add(col2)     ds.Tables.Add(stdTable)     ' Add Student Data to the table     Dim NewRow As DataRow = stdTable.NewRow()       NewRow("Name") = "Melanie Talmadge"     NewRow("Address") = "Meadowlake Dr, Dtown"     stdTable.Rows.Add(NewRow)     NewRow = stdTable.NewRow()       NewRow("Name") = "Amy Talmadge"       NewRow("Address") = "Herndon"     stdTable.Rows.Add(NewRow)     ds.AcceptChanges()     ' Create a new StreamWriter     ' We'll save data in stdData.xml file     Dim writer As System.IO.StreamWriter = _     New System.IO.StreamWriter("c:\\stdData.xml")     ' Writer data to DataSet which actually creates the file     ds.WriteXml(writer)     writer.Close()     Catch exp As Exception       Console.WriteLine("Exception: {0}", exp.ToString())     End Try   End Sub End Module 
end example

You wouldn't believe what the WriteXml method does for you. Take a peek at the output stdData.xml file; it generates a standard XML file that looks like Listing 6-21.

Listing 6-21: WriteXml Method Output

start example
 - <DS xmlns="StdNamespace"> - <Student> <Name>Melanie Talmadge</Name> <Address>Meadowlake Dr, Dtown</Address> </Student> - <Student> <Name>Amy Talmadge</Name> <Address>Herndon</Address> </Student> </DS> 
end example

Using the WriteXmlSchema Method

The WriteXmlSchema method writes a DataSet structure to an XML schema. WriteXmlSchema has four overloaded methods. You can write the data to a stream, text, TextWriter, or XmlWriter. Listing 6-22 uses XmlWriter for the output.

Listing 6-22: Using the WriteXmlSchema Method

start example
 Dim ds As DataSet = New DataSet("DS") ds.Namespace = "StdNamespace" Dim stdTable As DataTable = New DataTable("Students") Dim col1 As DataColumn = New DataColumn("Name") Dim col2 As DataColumn = New DataColumn("Address") stdTable.Columns.Add(col1) stdTable.Columns.Add(col2) ds.Tables.Add(stdTable) ' Add Student Data to the table Dim NewRow As DataRow = stdTable.NewRow() NewRow("Name") = "Melnaie Talmadge" NewRow("Address") = "Meadowlake Dr, Dtown" stdTable.Rows.Add(NewRow) NewRow = stdTable.NewRow() NewRow("Name") = "Amy Talmadge" NewRow("Address") = "Herndon, VA" stdTable.Rows.Add(NewRow) ds.AcceptChanges() Dim writer As XmlTextWriter =    New XmlTextWriter(Console.Out) ds.WriteXmlSchema(writer) 
end example

Refer to the previous section to see how to create an XmlTextWriter object.

Using XmlDataDocument and XML

As discussed earlier in this chapter, the XmlDocument class provides a DOM tree structure of XML documents. The XmlDataDocument class comes from XmlDocument, which comes from XmlNode. Figure 6-6 shows the XmlDataDocument class inheritance.


Figure 6-6: The XmlDataDocument class inheritance

Besides overriding the methods of XmlNode and XmlDocument, XmlDataDocument also implements its own methods. The XmlDataDocument class lets you load relational data using the DataSet object as well as XML documents using the Load and LoadXml methods. As Figure 6-7 indicates, you can use a DataSet to load relational data to an XmlDataDocument object and use the Load or LoadXml methods to load an XML document. Figure 6-7 shows the relationship between a Reader, Writer, DataSet, and XmlDataDocument.

click to expand
Figure 6-7: Reading and writing data using XmlDataDocument

The XmlDataDocument class extends the functionality of XmlDocument and synchronizes it with a DataSet. As you know, a DataSet is a powerful object in ADO.NET. As Figure 6-7 shows, you can take data from two different sources. First, you can load data from an XML document with the help of XmlReader, and second, you can load data from relational data sources with the help of database providers and a DataSet. The neat thing is the data synchronization between these two objects. If you update data in a DataSet object, you see the results in the XmlDataDocument object—and vice versa. For example, if you add a record to a DataSet object, the action will add one node to the XmlDataDocument object representing the newly added record.

Once the data is loaded, you're allowed to use any operations that you're able to use on XmlDocument objects. You can also use XmlReader and XmlWriter objects to read and write the data.

The XmlDataDocument class has a property called DataSet. It returns the attached DataSet object with XmlDataDocument. The DataSet property provides you a relational representation of an XML document. Once you have a DataSet object, you can do anything with it that you did in Chapters 3 and 4, such as binding it to data-bound controls.

You can use all the XML read and write methods of the DataSet object (such as ReadXml, ReadXmlSchema, WriteXml, and WriteXmlSchema) through the DataSet property. Refer to the DataSet read and write methods in the previous section to see how these methods are used.

Loading Data Using Load and LoadXml from the XmlDataDocument

You can use either the Load method or the LoadXml method to load an XML document. The Load method takes a parameter of a filename string, a TextReader, or an XmlReader. Similarly, you can use the LoadXml method. This method passes an XML filename to load the XML file. For example:

 Dim doc As XmlDataDocument = New XmlDataDocument() doc.Load("C:\\Books.xml") 

Or you can load an XML fragment, as in the following example:

 Dim doc As XmlDataDocument = New XmlDataDocument() doc.LoadXml("<Record> write something</Record>") 

Loading Data Using a DataSet

As you learned in Chapter 3, a DataSet object has methods to read XML documents. These methods are ReadXmlSchema and LoadXml. You use the Load or LoadXml methods to load an XML document the same way you did directly from XMLDataDocument. Again, the Load method takes a parameter of a filename string, TextReader, or XmlReader. Similarly, use the LoadXml method to pass an XML filename through the DataSet. For example:

 Dim doc As XmlDataDocument = New XmlDataDocument() doc.DataSet.ReadXmlSchema("test.xsd") 

or as follows:

 doc.DataSet.ReadXml("<Record> write something</Record>") 

Displaying XML Data in a DataSet Format

As mentioned previously, you can get a DataSet object from an XmlDataDocument object by using its DataSet property. OK, now it's time to see how to do that. The next sample shows you how easy it is to display an XML document data in a DataSet format.

You can read an XML document using the ReadXml method of the DataSet object. The DataSet property of XmlDataDocument represents the DataSet of XmlDataDocument. After reading a document in a DataSet, you can create data views from the DataSet, or you can also use a DataSet's DefaultViewManager property to bind to data-bound controls, as you can see in the following code:

  Dim xmlDatadoc As XmlDataDocument = New XmlDataDocument() xmlDatadoc.DataSet.ReadXml("C:\\XmlDataDoc.xml")  dataGrid1.DataSource = xmlDatadoc.DataSet.DefaultViewManager 

As you can see from Listing 6-23, you create a new DataSet, Books, fill it from the books.xml file, and bind it to a DataGrid control using its DataSource property. To make Listing 6-23 work, you need to create a Windows application and drag a DataGrid control to the form. After doing that, write the Listing 6-23 code on the form load event.

Listing 6-23: XmlDataDocumentSample.vb

start example
 Private Sub Form1_Load(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles MyBase.Load     ' Create an XmlDataDocument object and read an XML     Dim xmlDatadoc As XmlDataDocument = New XmlDataDocument()     xmlDatadoc.DataSet.ReadXml("C:\\books.xml")     ' Create a DataSet object and fill it with the dataset     ' of XmlDataDocument     Dim ds As DataSet = New DataSet("Books DataSet")     ds = xmlDatadoc.DataSet     ' Attach dataset view to the DataGrid control     DataGrid1.DataSource = ds.DefaultViewManager End Sub 
end example

If you run this program, you'll see the DataGrid filled with the data.

Saving Data from a DataSet to XML

You can save a DataSet as an XML document using the Save method of the XmlDataDocument class. Actually, XmlDataDocument comes from XmlDocument, and the XmlDocument class defines the Save method. As you know, you can use Save method to save your data in a string, stream, TextWriter, and XmlWriter.

First, you create a DataSet object and fill it using a DataAdapter. The following example reads the Customers table from the Northwind Access database and fills data from the table to the DataSet:

 Dim sql As String = "SELECT * FROM Customers" Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn) ' Create and fill a DataSet Dim ds As DataSet = New DataSet() da.Fill(ds) 

Now, you create an instance of XmlDataDocument with the DataSet as an argument and call the Save method to save the data as an XML document:

 Dim doc As XmlDataDocument = New XmlDataDocument(ds) doc.Save("C:\\XmlDataDoc.xml") 

Listing 6-24 shows a complete program. You create an XmlDataDocument object with a DataSet and call the Save method to save the DataSet data in an XML file.

Listing 6-24: Saving the DataSet Data to an XML Document

start example
 Imports System.Data Imports System.Data.SqlClient Imports System.Xml Module Module1   Sub Main()     ' Create a Connection Object     Dim ConnectionString As String = "Integrated Security=SSPI;" & _      "Initial Catalog=Northwind;Data Source=MCB;"     Dim conn As SqlConnection = New SqlConnection()     conn.ConnectionString = ConnectionString     ' Open the connection     If conn.State <> ConnectionState.Open Then       conn.Open()     End If     Dim sql As String = "SELECT * FROM Customers"     Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)     ' Create and fill a DataSet     Dim ds As DataSet = New DataSet()     da.Fill(ds)     ' Now use SxlDataDocument's Save method to save data as an XML file     Dim doc As XmlDataDocument = New XmlDataDocument(ds)     doc.Save("C:\\XmlDataDoc.xml")     ' Close and dispose the connection     If conn.State <> ConnectionState.Open Then       conn.Open()       conn.Dispose()     End If   End Sub End Module 
end example

XmlDataDocument: Looking under the Hood

After looking at Listing 6-23, which illustrates the reading of an XML document in a DataGrid control, you must be wondering how it happened. The DataSet object handles everything for you under the hood:

 doc.DataSet.ReadXml("C:\\outdata.xml") 

As you see in this line, you're calling the DataSet.ReadXml method to read an XML document. The DataSet extracts the document and defines tables and columns for you.

Generally, the root node of the XML document becomes a table; the document's name, namespace, namespace URI, and prefix become the DataSet's Name, Namespace, NamespaceURI, and Prefix properties, respectively. If an element's children have one or more children, they become another table inside the main table in a nested format. Anything left from the tables becomes columns of the table. The value of a node becomes a row in a table. The DataSet takes care of all of this for you.




Applied ADO. NET(c) Building Data-Driven Solutions
Applied ADO.NET: Building Data-Driven Solutions
ISBN: 1590590732
EAN: 2147483647
Year: 2006
Pages: 214

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net