8.9. Formatting Column Values When Outputting Data as XML

Problem

You need to save some of the columns in a DataTable as attributes instead of elements when you write out the data as XML.

Solution

Use the ColumnMapping property.

The sample code contains two event handlers:

Form.Load

Sets up the sample by creating a DataSet containing the first two records of the Customers table from Northwind.

Refresh Button.Click

Iterates over all of the columns in all of the Customers tables and sets the ColumnMapping property to the specified value. The ColumnMapping for the ContactName column is then set to the specified value. The XML output for the DataSet is displayed.

The C# code is shown in Example 8-13.

Example 8-13. File: XmlElementsOrAttributesForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; private DataSet ds; // . . . private void XmlElementsOrAttributesForm_Load(object sender, System.EventArgs e) { ds = new DataSet("CustomersDataSet"); // Get the top two rows from the Customers table. SqlDataAdapter da = new SqlDataAdapter( "SELECT TOP 2 * FROM Customers", ConfigurationSettings.AppSettings["Sql_ConnectString"]); da.Fill(ds, "Customers"); } private void refreshButton_Click(object sender, System.EventArgs e) { // Set the mapping type for each column in the table. foreach(DataTable table in ds.Tables) foreach(DataColumn column in table.Columns) { if(tableAttributeRadioButton.Checked) column.ColumnMapping ...

Get ADO.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.