bladestonight has asked for the wisdom of the Perl Monks concerning the following question:
I was trying to change some elements in my tree into attributes for other elements. Whilst creating the same subroutines over and over with only the new parent node changing, I thought there has to be a better way.
I created a generic subroutine which deletes the node and inserts it as an attribute for another element but I get the following error:
Can't call method "set_att" without a package or object reference at m +ine.pl line 40, <DATA> chunk 2.
I'm sure I'm missing something fundamental, here is some code to explain what I'm doing (see expected_doc for the result I'm looking for):
#!/usr/bin/perl -w use strict; use XML::Twig; $/="\n\n"; my $doc = <DATA>; # the original data set my $expected_doc = <DATA>; # result with elements changed to attribu +tes my $twig= new XML::Twig( # create the twig pretty_print => 'indented', twig_roots => { 'elt_att' => sub { addAtt(@_,'elt') }, 'selt_att' => sub { addAtt(@_,'subelt') }, }, ); $twig->parse($doc); $twig->flush; # Finished. exit(0); # Give a decent error message if we wrote to stdout and had disk full. END { close(STDOUT) || die "ERROR: can't close stdout: $!\n" } #===================================================================== +========== # Subroutines #--------------------------------------------------------------------- +---------- sub addAtt { my( $t, $att,$parent)= @_; my $e_parent = $t->findnodes($parent); $e_parent->set_att($att->gi,$att->trimmed_text); $att->delete; $t->flush; } __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> <doc> <elt elt_class="class1" elt_att="elt_att1"> <subelt subelt_class="sclass1"> <content id="content1"/> </subelt> <elt elt_class="class2"> <subelt subelt_class="sclass2" selt_att="selt_att1"> <content id="content2"/> </subelt> </elt> <elt elt_class="class3" elt_att="elt_att1"> <subelt subelt_class="sclass3"> <content id="content3"/> </subelt> </elt> </doc>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XML::Twig creating generic subroutine for attributes
by mirod (Canon) on Apr 19, 2007 at 09:21 UTC | |
|
Re: XML::Twig creating generic subroutine for attributes
by Jenda (Abbot) on Apr 19, 2007 at 09:34 UTC | |
by bladestonight (Novice) on Apr 19, 2007 at 12:45 UTC |