in reply to XML::Twig creating generic subroutine for attributes
There are several problems with your code:
If you use twig_roots, then anything outside of the roots is ignored, except for the root of the XML. So if you don't set elt as a root, then you won't see it. I think the simplest would be for you to replace twig_roots by twig_handlers, so you can access anything in the XML. If the XML you are processing is too bug to fit in memory, you can set a twig handler on elt that will flush it. It would be the best place to flush in any case, as the logical tree you work on is an elt.
Then you use findnodes, which returns a list of elements that match the XPath query (and a query like 'elt' will always return an empty list, it is a syntactically valid but useless query, hence the error you get when you call set_att on an empty $e_parent). Instead what you want is either the parent elt, or the previous subelt, which you can get in both cases by using the prev_elt method. So here is a modified setAtt function, that produces the results you want (I also renamed $att as $elt, I was getting confused, and also you don't ant to use the trimmed_text of the element as value of the new attribute, but instead the value of the att attribute of the element you are processing):
sub addAtt { my( $t, $elt, $parent)= @_; my $e_parent = $elt->prev_elt($parent); if( !$e_parent) { die "no parent '$parent' for element '", $elt->g +i, "'\n"; } $e_parent->set_att($elt->gi,$elt->att( 'att')); $elt->delete; $t->flush; }
|
|---|