XML output from MySQL XML output from MySQL xml xml

XML output from MySQL


The mysql command can output XML directly, using the --xml option, which is available at least as far back as MySql 4.1.

However, this doesn't allow you to customize the structure of the XML output. It will output something like this:

<?xml version="1.0"?><resultset statement="SELECT * FROM orders" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <row>    <field name="emp_id">129</field>    <field name="cust_id">107</field>    <field name="region">Eastern</field>  </row></resultset>

And you want:

<?xml version="1.0"?><orders>  <employee emp_id="129">    <customer cust_id="107" region="Eastern"/>  </employee></orders>

The transformation can be done with XSLT using a script like this:

<?xml version="1.0"?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">  <xsl:output indent="yes"/>  <xsl:strip-space elements="*"/>  <xsl:template match="resultset">    <orders>      <xsl:apply-templates/>    </orders>  </xsl:template>  <xsl:template match="row">    <employee emp_id="{field[@name='emp_id']}">      <customer        cust_id="{field[@name='cust_id']}"        region="{field[@name='region']}"/>    </employee>  </xsl:template></xsl:stylesheet>

This is obviously way more verbose than the concise MSSQL syntax, but on the other hand it is a lot more powerful and can do all sorts of things that wouldn't be possible in MSSQL.

If you use a command-line XSLT processor such as xsltproc or saxon, you can pipe the output of mysql directly into the XSLT program. For example:

mysql -e 'select * from table' -X database | xsltproc script.xsl -


Using XML with MySQL seems to be a good place to start with various different ways to get from MySQL query to XML.

From the article:

   use strict;   use DBI;   use XML::Generator::DBI;   use XML::Handler::YAWriter;   my $dbh = DBI->connect ("DBI:mysql:test",                           "testuser", "testpass",                           { RaiseError => 1, PrintError => 0});   my $out = XML::Handler::YAWriter->new (AsFile => "-");   my $gen = XML::Generator::DBI->new (                                   Handler => $out,                                   dbh => $dbh                               );   $gen->execute ("SELECT name, category FROM animal");   $dbh->disconnect ();