XML output from MySQL

纵然是瞬间 提交于 2019-11-27 15:33:50
soldier.moth

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 ();

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 -
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!