< Day Day Up > |
Generating XML from a DataTableOne question I receive quite often regarding serializing ADO.NET objects to XML format is how to generate XML from a standalone DataTable, or one that is not included in a parent DataSet object. If you look up the GetXml or WriteXml method in online help, you'll find that while both methods are implemented by the DataSet class, neither is implemented by the DataTable class. This is a bit confusing at first because, as you've seen, calling and using these methods against a DataSet containing multiple DataTable objects does result in each table being processed. After exchanging a couple of e-mails with friends on the .NET development team, I've found that the DataSet does define methods to serialize a specified DataTable, but that these methods are not exposed. However, this limitation is very easy to circumvent with the following generic function�WriteDataTableToXml�which serializes a specified DataTable object to XML.
The WriteDataTableToXml function takes three parameters�a DataTable object, a String that's used as a file name, and an XmlWriteMode enumeration value. After the function constructs an empty DataSet, it checks to see if the DataTable already belongs to a DataSet by inspecting the DataTable::DataSet property. This is done due to the restriction that a single instance of a DataTable cannot simultaneously belong to more than one DataSet. If the DataTable does not belong to a DataSet, it is added to the temporary DataSet. If the table does belong to a DataSet, then a temporary copy of the DataTable is made and added to the temporary DataSet. Finally, the DataSet::WriteXml is called, passing it the specified file name and XmlWriteNode parameter values. The following test function programmatically constructs a DataTable, defining its columns and adding a couple of rows of test data before calling the WriteDataTableToXml function.
As the following output indicates, our little helper function now enables us to serialize DataTable objects with or without the accompanying schema information.
|
< Day Day Up > |
No comments:
Post a Comment