DataSet & XML

Source: Internet
Author: User
Preface

Before discussing DataSet and XML, we should first have a preliminary understanding of ADO. NET. ADO. NET is the latest in a variety of data access technologies, and it has become a building.. Net database application, despite this, ADO. NET is not fully database-centric. It integrates XML support and provides platform interoperability and Scalable Data Access (this is also ADO. NET and ADO ).
In ADO. in the. NET Component, DataSet is one of its core components. It provides data access independent from the data source. To achieve this platform's Interoperability and Scalable Data Access, ADO. NET adopts the XML-based Data Transmission Format, where XML plays a crucial role. During data transmission, ADO. NET expresses DataSet as XML and then transmits it to other components in XML format. This design of DataSet allows us to use XML to easily transmit data through the Web. Of course, the component for receiving data is not necessarily ADO.. NET component. It can be any component that can process XML data. From here, we can see that ADO. NET is more powerful than ADO.
Figure 1 illustrates the relationship between. NET data providers, DataSet, and XML:

Figure 1

Convert data from DataSet to XML

To better illustrate the relationship between DataSet and XML, we use the VS. NET environment to develop two examples.
The following example shows how to use ADO. NET to write DataSet data to an XML file. We use the Pubs library that comes with SQL Server2000 to generate an XML file about the author (Authors) information. First, create a Windows application named DataToXml and open. NET, perform the following steps: file --> New --> project. The window 2 is displayed. Enter the Project name: DataToXml, save the project location, and click "OK ", after the project is created,. NET creates a Windows Form named Form1 by default (Figure 3 ).

Figure 2

Figure 3

Next, create a Form for operating the DataSet and create a Windows Form named DataToXmlSample. Perform the following steps: Right-click DataToXml --> Add -- add Windows form (figure 4) in the Project Resource Manager. The create "Add new project" window is displayed, and enter DataToXmlSample (figure 5 ). Of course, you can also change the name of the Form1 created by VS. NET when VS. NET creates a Windows project to the file name we need.

Figure 4

Figure 5

Add the required control to the DataToXmlSample form. In this example, we need a ListBox named lbxXmlData to view the information retrieved from the database. There are two Button buttons, and one is btnViewXml, one is btnBuildFile, and the other six controls are easily arranged on the form. After setting the form, we will proceed with the most critical coding work.

Figure 6

To run this example, You need to import the Data, Xml, Data SqlClient, and IO namespace. First, we start from creating DataSet and create the CreateDataSet () method. The return type is DataSet. In this way, you can directly call this method in other methods to obtain DataSet.

Public DataSet CreateDateSet ()

{

// Create a connection to the SQL Server database

Stringstrconn = "DataSource = localhost; Database = Pubs; uid = sa; pwd = ";

Sqlconnection conn = new sqlconnection ();

Conn. connectionstring = strconn;

Conn. open ();

// Create a dataset about the authors table

String strauthorssql = "select * from authors ";

Sqldataadapter da = new sqldataadapter (strauthorssql, Conn );

Da. selectcommand. commandtype = commandtype. text;

// Declare DataSet

DataSet ds = new DataSet ();

Da. Fill (ds, "XMLAuthors ");

// Return the DataSet

Return ds;

}

Next, write the code to generate the Xml data stream and compile the BuildXml () method:

Public XmlDocument BuildXml ()

{

// Declare the MemoryStream object

XmlDocument doc = new XmlDocument ();

MemoryStream mStrm = new MemoryStream ();

StreamReader sRead = new StreamReader (mStrm );

// Call the CreateDataSet method to output data in DataSet

CreateDateSet (). WriteXml (mStrm, XmlWriteMode. IgnoreSchema );

// Search from the beginning of the data stream

MStrm. Seek (0, SeekOrigin. Begin );

// Load the data stream to XmlDocument

Doc. Load (sRead );

Return doc;

}

BuildFile ():

Private void BuildFile ()

{

// Path of the file to be written

String filepath = "F: \ Authors. xml ";

CreateDateSet (). WriteXml (filepath );

}

Now that we have completed all the basic work, we need to combine these methods to achieve our goal. Return to the design window, double-click "View Xml", and switch to the code editing window. The system automatically adds the btnViewXml_Click () method. In this method, we add the following code to fill the XML data stream into The ListBox control.

Private void btnViewXml_Click (object sender, System. EventArgs e)

{

// Clear all items in ListBox

LbxXmlData. Items. Clear ();

XmlNodeList ndList = BuildXml (). GetElementsByTagName ("XMLAuthors ");

Foreach (XmlNode xn in ndList)

LbxXmlData. Items. Add (xn. InnerText );

}

Return to the design window again, double-click the "Build File" button, switch to the code editing window, and add the following code in the btnBuildFile_Click () method automatically added by the system to call BuildFile () above () method to generate Authors. xml file.

Private void btnBuildFile_Click (object sender, System. EventArgs e)

{

BuildFile ();

}

In order for our windows application to run, we also need to provide an entry point for the program:

[Stathread]

Static void main ()

{

Application. Run (New datatoxmlsample ());

}

Now, all the coding work of this program has been completed. Let's taste the fruits of our work! Double-click the "Start" button on the Vs. Net toolbar to start the application. The 7 window is displayed. Click the "view XML" button to call the btnviewxml_click () method. The ListBox is filled with records (figure 8 ). Click the "Build File" button, call the btnbuildfile_click () method, and generate authors. XML (9) under the root directory of drive F ).

 

Figure 7 Figure 8

Figure 9

So far, our first example: the conversion from dataset to XML has been completed successfully. In the next example, we need to fill the data in the generated authors. xml file into dataset to complete a data loop.

Convert XML data to DataSet data
Create an XmlToData project as you just created a DataToXml project, and add a Form in the project named XmlToDataSetSample. Add a vertex rad control named dgViewXml and a Button control named btmLoadXml to the form. Click the "Load Xml" button to switch to the code editing window. Enter the following code:

Private void btnLoadXml_Click (object sender, System. EventArgs e)

{

DataSet ds = new DataSet ();

String filepath = "F: \ Authors. xml ";

Ds. ReadXml (filepath );

DgViewXml. DataSource = ds;

DgViewXml. DataMember = "XMLAuthors ";

}

Add a program entry point:

[STAThread]

Static void Main ()

{

Application. Run (new XmlToDataSetSample ());

}

Click the "Start" button on the toolbar, start the application (10), click the "Load Xml" button, the program calls the btnLoadXml_Click () method, and put Authors. the data in xml is filled in DataSet and displayed in the DataGrid Control (figure 11 ).

Figure 10

Figure 11

Conclusion

. NET Framework provides powerful support for operating XML. In. NET Framework, DataSet and XML documents are different views of the same data. ADO. NET's support for XML provides easy-to-develop solutions for data sharing between applications, changing the face of a typical distributed system.

About the author

Xu Jiabao, CNet, is now working in the development of the website information publishing system of Beijing Qianlong News Network Communication Co., Ltd., often at the CCW developer Club (Dev-Club. NET activities, for Microsoft. NET technology is very interested, like XML technology, just. NET related technologies have been contributed to CSDN's "programmer" magazine. Currently, the main technologies involved include Windows DNA,. NET, XML, and SOAP. You can contact him through the jiabaoxu@hotmail.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.