| Processing XML with Perl |    | Michel Rodriguez | 
 ![]() Example: Data Base Integration  |     |  ![]() Resources  |  
Example: Data Base Integration (cont'd)
the script:
#!/bin/perl -w
use strict;
use DBI;
use XML::Twig;
my $file= shift;
my $dbh= connect_to_db();
my $twig= new XML::Twig( TwigRoots => { book => \&book }, # only process include elements
                         TwigPrintOutsideRoots => 1,);          # output the rest unchanged
$twig->parsefile( $file);
$dbh->disconnect();
exit;
# connect to the data base
sub connect_to_db
  { my $driver = "mysql";
    my $dsn = "DBI:$driver:database=test;";
    my $dbh = DBI->connect($dsn, 'test', '', {AutoCommit=>1});
    my $drh = DBI->install_driver($driver);
    return( $dbh);
  }
sub book
  { my( $twig, $book)= @_;
    my $field= $book->att( 'field');
    my $code=  $book->att( 'code');
    my $query= "select $field from books where code='$code'";; 
    # prepare the select
    my $sth= $dbh->prepare( $query);
    $sth->execute();
    my $row= $sth->fetchrow_arrayref();      # there will be only one row
    print $row->[0];                         # and one field in the row
   }
     
  |  
 ![]() Example: Data Base Integration  |     |  ![]() Resources  |  
 

