With a single mysqldump command, you can export a subset of your MySQL database to an XML file. This can save you considerable time in writing a script or application to selectively write out the appropriate data to XML. Here is how you do this…
Let’s say you have this data…
mysql> select * from Month;
+---------+-----------+
| MonthID | Name |
+---------+-----------+
| 1 | January |
| 2 | February |
| 3 | March |
| 4 | April |
| 5 | May |
| 6 | June |
| 7 | July |
| 8 | August |
| 9 | September |
| 10 | October |
| 11 | November |
| 12 | December |
+---------+-----------+
12 rows in set (0.00 sec)
Now, let’s say you only want to export the months ending in "ber" to XML. You can execute the following command to do this…
mysqldump -q -X -t -w "Name like '%ber'" mydatabase Month
In this command, the -q turns off buffering of the results (appropriate for large tables), the -X specifies XML output, the -t specifies to turn off writing table meta data, the -w specifies a WHERE clause to run (omit this switch to export all data), the mydatabase is the name of the database, and Month is the name of the table to export.
This results in the following…
<?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="realmetrics">
<table_data name="Month">
<row>
<field name="MonthID">9</field>
<field name="Name">September</field>
</row>
<row>
<field name="MonthID">10</field>
<field name="Name">October</field>
</row>
<row>
<field name="MonthID">11</field>
<field name="Name">November</field>
</row>
<row>
<field name="MonthID">12</field>
<field name="Name">December</field>
</row>
</table_data>
</database>
</mysqldump>
Now, let’s say you want to exclude the "MonthID" field from the results, you could do this by executing the following under Linux…
mysqldump -q -X -t -w "Name like '%ber'" mydatabase Month | fgrep -v "name=\"MonthID\""
This command results in…
<?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="realmetrics">
<table_data name="Month">
<row>
<field name="Name">September</field>
</row>
<row>
<field name="Name">October</field>
</row>
<row>
<field name="Name">November</field>
</row>
<row>
<field name="Name">December</field>
</row>
</table_data>
</database>
</mysqldump>
This example is simple but you might use this technique to export all of a customer’s data to XML if requested.