2 things can help you here: you can use start_tag_handlers, which are called after the start tag of the element has been parsed (and the element object has been created, empty at that point). This also means taht the UML:Attribute element will get completely parsed before the UML:Class, but when you're in their handler the opening tag of UML:Class has already been parsed. If you don't use twig_roots but regular twig_handlers the element exists, it's an ancestor of the UML:Attribute element, and it's attributes are already available. If space is a problem, you cant sprinkle purge call to taste.

So in your case I would write something like (untested):

use strict; use warnings; use Data::Dumper; use XML::Twig; my $twig = XML::Twig->new( start_tag_handlers => { 'UML:Class' => \&ulm_class, }, twig_handlers => { 'UML:Class' => sub { $_[0]->purge }, # purg +e at the end of each section, 'UML:Attribute' => \&uml_attr, } ); $twig->parsefile( 'testfile.xmi' ); sub uml_class { my ( $twig, $section ) = @_; print "data for class:\n"; print " name = ", $section->att( 'name' ), "\n"; print " xmi.id = ", $section->att( 'xmi.id' ), "\n"; } sub uml_attr { my ( $twig, $attr ) = @_; # if you need the class id, it's in $attr->parent( ''UML:Class')-> +attr( 'xmi.id') $attr->print; print Dumper( $struct ); # parse the block and extract the data elements $twig->purge; }

Does it make sense? It probably doesn't matter that much if your files are small, but it feels better to parse only once each section.


In reply to Re^5: Pulling out sections of an XMI file with XML::Twig by mirod
in thread Pulling out sections of an XMI file with XML::Twig by bobf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.