Database Reference
In-Depth Information
</row>
<row>
<subject>Jane</subject>
<test>B</test>
<score>50</score>
</row>
…
<row>
<subject>Marvin</subject>
<test>C</test>
<score>53</score>
</row>
<row>
<subject>Marvin</subject>
<test>D</test>
</row>
</select>
</rowset>
Each table row is written as a
<row>
element. Within a row, column names and values
are used as element names and values, one element per column. Note that
NULL
values
are omitted from the output.
The script produces this output with very little code after it processes the command-
line arguments and connects to the MySQL server. The XML-related parts of
mysql_to_xml.pl
are the
use
statements that pull in the necessary modules and the code
to set up and use the XML objects. Given a database handle
$dbh
and a query string
$query
, the code instructs the writer object to send its results to the standard output,
then connects that object to DBI and issues the query:
#!/usr/bin/perl
# mysql_to_xml.pl: Given a database and table name,
# dump the table to the standard output in XML format.
use
strict
;
use
warnings
;
use
DBI
;
use
XML::Generator::
DBI
;
use
XML::Handler::
YAWriter
;
#
...
process
command
-
line
options
(
not
shown
)
...
#
...
connect
to
database
(
not
shown
)
...
# Create output writer; "-" means "standard output"
my
$out
=
XML::Handler::
YAWriter
->
new
(
AsFile
=>
"-"
);
# Set up connection between DBI and output writer
my
$gen
=
XML::Generator::
DBI
->
new
(
dbh
=>
$dbh
,
# database handle
Handler
=>
$out
,
# output writer
RootElement
=>
"rowset"
# document root element
);