Hi, I was wondering if someone could point me in the right direction. In
my example below, I have a handler that will parse a contact's name into
another xml node. However, the problem is that when I do this, the
parent node loses an attribute that I am trying to set. Here is example
output:

<addressbook>
<contact new="1">
<email>[EMAIL PROTECTED]</email>
</contact>
<contact>
<nickname>Joe Schmoe</nickname>
<first-name>Joe</first-name>
<last-name>Schmoe</last-name>
<email>[EMAIL PROTECTED]</email>
</contact>
</addressbook>

Notice how the second contact node is missing the "new=1" attribute. If anyone
can enlighten me on the correct way to address this problem, I would be quite
grateful.


-----------------------------------------
#!/usr/bin/perl

use XML::Twig;

# the old_tag => new_tag table
my %change=
  ( contacts => 'addressbook',
    emailOne => 'email',
    lastFirstName => 'nickname',
  );

# let's build the StartTagHandlers
my $handlers;
while( my( $old_tag, $new_tag)= each( %change) ) {
    $handlers->{$old_tag}= sub { $_[1]->set_gi( $new_tag); };
}

my $twig_handlers = {
                    'contact' => \&begin_contact,
                    'lastFirstName' => \&contact_name,
                    };

my $twig= new XML::Twig(
                     TwigHandlers => $twig_handlers,
                    StartTagHandlers => $handlers,
                     );
# long example line, normally we would parse this from a file
$twig->parse('<contacts><contact><emailOne>[EMAIL 
PROTECTED]</emailOne></contact><contact><lastFirstName>Joe 
Schmoe</lastFirstName><emailOne>[EMAIL 
PROTECTED]</emailOne></contact></contacts>'); 
$twig->flush;

sub begin_contact {
    my ($twig, $contact) = @_;
    $contact->set_att(new=>"1");
    $twig->flush;
}

sub contact_name {
    my ($twig, $contact_name) = @_;
    my ($first, $last) = split (/ /, $contact_name->first_child_text);
    if (defined($last)) {
        $contact_name->insert_new_elt('after','last-name',$last);
    }
    if (defined($first)) {
        $contact_name->insert_new_elt('after','first-name',$first);
    }
    $twig->flush;
}


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to