#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $CATALOG_FILE = "plant_catalog.xml";
my $UPDATE_FILE  = "updates.xml";

my $updates= XML::Twig->new->parsefile( $UPDATE_FILE);

                                                # element => subroutine
my $catalog=  XML::Twig->new( twig_handlers => { plant    => \&plant, },
                              pretty_print => 'indented',
                            );

$catalog->parsefile( $CATALOG_FILE);
$catalog->flush;

exit;

sub plant
  { my( $twig, $plant)= @_;
  
    my $id= $plant->att( 'id');
    my $update= $updates->elt_id( $id);  # updates is global

    if( $update)
      { foreach my $updated ( $update->children)
          { my $field    = $updated->tag;
            my $original_elt= $plant->first_child( $field);
            $original_elt->replace_with( $updated);
            warn "updating $id - $field: ", $original_elt->text, " => ", $updated->text, "\n";
          }
      }
    $twig->flush; # prints the XML so far, and frees the memory
  }
