XML output from MySQL

NumberFour picture NumberFour · May 17, 2010 · Viewed 28.2k times · Source

is there any chance of getting the output from a MySQL query directly to XML?

Im referring to something like MSSQL has with SQL-XML plugin, for example:

SELECT * FROM table WHERE 1 FOR XML AUTO

returns text (or xml data type in MSSQL to be precise) which contains an XML markup structure generated according to the columns in the table.

With SQL-XML there is also an option of explicitly defining the output XML structure like this:

SELECT
  1       AS tag,
  NULL    AS parent,
  emp_id  AS [employee!1!emp_id],
  cust_id    AS [customer!2!cust_id],
  region    AS [customer!2!region]
 FROM table
 FOR XML EXPLICIT

which generates an XML code as follows:

<employee emp_id='129'>
   <customer cust_id='107' region='Eastern'/>
</employee>

Do you have any clues how to achieve this in MySQL?

Thanks in advance for your answers.

Answer

Neil Mayhew picture Neil Mayhew · Jan 15, 2014

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 -