Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Thomas Beutel http://www.beutelevision.com

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Cheap XML append in Perl

Here is a really cheap way in Perl to append an XML fragment to an existing XML doc. It appends it just before the last closing tag. Note that there is no validation or well-formedness checking. Use at your own risk. That said, it can be handy if you know that your XML is going to be OK.

   1  #!/usr/bin/perl
   2  
   3  sub xappend(\$$) { ${$_[0]} =~ s/(<\/[^>]+>\s*)$/$_[1]$1/s }
   4  
   5  $a = "<doc><item>foo</item></doc>";
   6  xappend($a,"<item>bar</item>");
   7  
   8  print $a; # prints <doc><item>foo</item><item>bar</item></doc>

From database records to XML

Here is a quick way to convert database records to XML using XML::Simple.

   1  
   2  #!/usr/bin/perl
   3  
   4  use warnings;
   5  use strict;
   6  use XML::Simple;
   7  use DBI;
   8  
   9  my $dbh = DBI->connect('DBI:mysql:MYDATABASE','user','password')
  10    or die DBI->errstr;
  11  
  12  # Get an array of hashes
  13  my $recs = $dbh->selectall_arrayref('SELECT * FROM contents',{ Columns => {} });
  14  
  15  # Convert to XML where each hash element becomes an XML element
  16  my $xml = XMLout( {record => $recs}, NoAttr => 1 );
  17  
  18  print $xml;
  19  
  20  $dbh->disconnect;


For a table with fields named "id", "entry", and "modified", the output would be:

   1  
   2  <opt>
   3    <record>
   4      <id>1</id>
   5      <entry>1932 - 1939</entry>
   6      <modified>2005-04-15 22:24:44</modified>
   7    </record>
   8    <record>
   9      <id>2</id>
  10      <entry>Yet another entry</entry>
  11      <modified>2005-04-15 22:25:00</modified>
  12    </record>
  13    <record>
  14      <id>3</id>
  15      <entry>More stuff here</entry>
  16      <modified>2005-04-15 22:25:13</modified>
  17    </record>
  18  </opt>

UTF8 Curly Quotes to ASCII

Here's a cheap hack to convert UTF8 curly quotes to ASCII (but try to use CPAN module instead of this if you can).

   1  
   2   $xml =~ s/\xe2\x80\x99/\'/gs;
   3   $xml =~ s/\xe2\x80\x98/\'/gs;
   4   $xml =~ s/\xe2\x80\x9c/\"/gs;
   5   $xml =~ s/\xe2\x80\x9d/\"/gs;
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS