[ Team LiB ] |
Recipe 8.9 Formatting Column Values When Outputting Data as XMLProblemYou need to save some of the columns in a DataTable as attributes instead of elements when you write out the data as XML. SolutionUse the ColumnMapping property. The sample code contains two event handlers:
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 = MappingType.Attribute; else if(tableElementRadioButton.Checked) column.ColumnMapping = MappingType.Element; else if(tableHiddenRadioButton.Checked) column.ColumnMapping = MappingType.Hidden; } // Set the mapping type for the ContactName column. DataColumn dc = ds.Tables["Customers"].Columns["ContactName"]; if(columnAttributeRadioButton.Checked) dc.ColumnMapping = MappingType.Attribute; else if(columnElementRadioButton.Checked) dc.ColumnMapping = MappingType.Element; else if(columnHiddenRadioButton.Checked) dc.ColumnMapping = MappingType.Hidden; else if(columnSimpleContentRadioButton.Checked) dc.ColumnMapping = MappingType.SimpleContent; // Display the XML. xmlTextBox.Text = ds.GetXml( ); } DiscussionThe ColumnMapping property of the DataColumn specifies how the value of a column will be written when the DataSet is output as an XML document with the GetXml( ) method or WriteXml( ) method. The property value is one of the MappingType enumeration values described in Table 8-5.
There is no way to set the ColumnMapping property for all columns in a DataTable or DataSet at once. Each column must be set individually. |
[ Team LiB ] |