in reply to XML::Twig creating generic subroutine for attributes

The problem is that the

my $e_parent = $t->findnodes($parent);
doesn't return anything. It does look a bit strange, but I don't know XML::Twig enough to be able to suggest the correct syntax. This is how the solution would look with XML::Rules:
use XML::Rules; my $parser = XML::Rules->new( style => 'filter', ident => ' ', rules => { _default => 'as array trim', elt => sub {delete $_[1]->{_content};$_[0] =>$_[1]}, 'elt_att,selt_att' => sub {$_[0] => $_[1]->{att}}, } ); $parser->filter(\*DATA); __DATA__ <doc> <elt elt_class="class1"> <subelt subelt_class="sclass1"> <content id="content1"/></subelt +> <elt_att att="elt_att1"></elt_att> </elt> <elt elt_class="class2"> <subelt subelt_class="sclass2"><content id="content2"/></subelt> <selt_att att="selt_att1"></selt_att> </elt> <elt elt_class="class3"> <subelt subelt_class="sclass3"><content id="content3"/></subelt> <elt_att att="elt_att1"></elt_att> </elt> </doc>

The rule for the <elt> is necessary because XML::Rules in the filter mode copies everything it parses as is until it encounters a tag with a custom rule so if there was no special rule for <elt> the module would copy the opening <elt> tag, the <subelt> tag with contents and then would process the <elt_att> and be unable to return back to the <elt> to add the results of the <elt_att> rule to the <elt> tag and would create a <elt_att>elt_att1</elt_att> tag.

Replies are listed 'Best First'.
Re^2: XML::Twig creating generic subroutine for attributes
by bladestonight (Novice) on Apr 19, 2007 at 12:45 UTC

    I only learnt about XML::Twig a week ago, I don't really want to learn about another module so soon just for this subroutine duplication problem. I'll keep XML::Rules in mind for the future though.

    Mirod, your solution worked when I changed twig_roots with twig_handlers and replaced my addAtt with your routine. Thanks very much.