15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

930 ❘ ChaPTer 33 mAnipulAtinG xml<br />

The XmlDataDocument is based on the XmlDocument class, so it has all of the functionality that the<br />

XmlDocument class has. One of the main differences is the overloaded constructor that the<br />

XmlDataDocument has. Note the line of code that instantiates XmlDataDocument (doc):<br />

doc = new XmlDataDocument(ds);<br />

It passes in the DataSet object that you created, ds, as a parameter. This creates the XML document<br />

from the DataSet, <strong>and</strong> you do not have to use the Load() method. In fact, if you instantiate a new<br />

XmlDataDocument object without passing in a DataSet as the parameter, it will contain a DataSet with<br />

the name NewDataSet that has no DataTables in the tables collection. There is also a DataSet property,<br />

which you can set after an XmlDataDocument-based object is created.<br />

Suppose that you add the following line of code after the DataSet.Fill() call:<br />

ds.WriteXml("c:\\test\\sample.xml", XmlWriteMode.WriteSchema);<br />

In this case, the following XML file, sample.xml, is produced in the folder c:\test:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

HL Road Frame-Black, 58<br />

1059.3100<br />

<br />

<br />

HL Road Frame-Red, 58<br />

1059.3100<br />

<br />

<br />

Sport-100 Helmet, Red<br />

13.0863<br />

<br />

<br />

Only the first couple of Products elements are shown. The actual XML file would contain all of the<br />

products in the Products table of Northwind database.<br />

Converting relational Data<br />

This looks simple enough for a single table, but what about relational data, such as multiple DataTables<br />

<strong>and</strong> Relations in the DataSet It all still works the same way. Here is an example using two related tables:<br />

private void button5_Click(object sender, EventArgs e)<br />

{<br />

XmlDocument doc = new XmlDocument();<br />

DataSet ds = new DataSet("XMLProducts");<br />

SqlConnection conn = new SqlConnection(_connectString);<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!