20.9. Using a DataSet to Read and Write XMLA powerful feature of ADO.NET is its ability to convert data stored in a data source to XML for exchanging data between applications in a portable format. Class DataSet of namespace System.Data provides methods WriteXml, ReadXml and GetXml, which enable developers to create XML documents from data sources and to convert data from XML into data sources. Writing Data from a Data Source to an XML DocumentThe application of Fig. 20.50 populates a DataSet with statistics about baseball players, then writes the data to an XML document and displays the XML in a TextBox. Figure 20.50. Writing the XML representation of a DataSet to a file.
We created this GUI by adding the Baseball.mdf database (located in the chapter's examples directory) as a data source, then dragging the Players node from the Data Sources window to the Form. This action created the BindingNavigator and DataGridView seen in the output of Fig. 20.50. We then added the Button btnWrite and the TextBox txtOutput. The XML representation of the Players table should not be edited and will span more lines than the TextBox can display at once, so we set txtOutput's ReadOnly and MultiLine properties to TRue and its ScrollBars property to Vertical. Create the event handler for btnWrite by double clicking it in Design view. The autogenerated FrmXMLWriter_Load event handler (lines 1622) calls method Fill of class PlayersTableAdapter to populate BaseballDataSet with data from the Players table in the Baseball database. Note that the IDE binds the DataGridView to BaseballDataSet.Players (through the PlayersBindingSource) to display the information to the user. Lines 2537 define the event handler for the Write to XML button. When the user clicks this button, line 29 sets BaseballDataSet's Namespace property to specify a namespace for the DataSet and any XML documents based on the DataSet (see Section 19.4 to learn about XML namespaces). Line 32 invokes DataSet method WriteXml, which generates an XML representation of the data contained in the DataSet, then writes the XML to the specified file. This file is created in the project's bin/Debug or bin/Release directory, depending on how you executed the program. Lines 3536 then display this XML representation. Line 36 invokes DataSet method GetXml, which returns a String containing the XML. Examining an XML Document Generated By DataSet Method WriteXmlFigure 20.51 presents the Players.xml document generated by DataSet method WriteXml in Fig. 20.50. Note that the BaseballDataSet root element (line 2) declares the document's default namespace to be the namespace specified in line 29 of Fig. 20.50. Each Players element represents a record in the Players table. The PlayerID, FirstName, LastName and BattingAverage elements correspond to the columns with these names in the Players database table. Figure 20.51. XML document generated from BaseballDataSet in XMLWriter.
|