in reply to Re: how to display descendants in XML with Perl's XML::Twig
in thread how to display descendants in XML with Perl's XML::Twig

Thanks for the code. The problem with using this is that the XML file I am working on is 300 mb and highly nested. Each child has diffrent levels of nesting. The if else would be tedious to use. My other question What if I had nested children within nested children? What would be the most efficient to do it? For example how do I access the elements of elt for each C? My 2nd question is about how I could display these elements like
The book of pages|Snap|Line1|Line2|Line3|Line4|Line5|C1.X| The book of pages|Snap|Line1|Line2|Line3|Line4|Line5|C1.Y| The book of pages|Snap|Line1|Line2|Line3|Line4|Line5|C2.X| The book of pages|Snap|Line1|Line2|Line3|Line4|Line5|C2.Y| The book of pages|Snap|Line1|Line2|Line3|Line4|Line5|C3.X| The book of pages|Snap|Line1|Line2|Line3|Line4|Line5|C3.Y| . . . . . The song|Snap|Line1|Line2|Line3|Line4|Line5|C2.X| The song|Snap|Line1|Line2|Line3|Line4|Line5|C2.Y| Example <Rating> <C1> <elt> <X></X> <X></X> </elt> <elt> <elt> </C1> <C2> <elt> <elt> <elt> </C2> <C3> <elt> <elt> <elt> </C3> </Rating>
Is there another XML module that can be more helpful than XML::Twig for this purpose?

Replies are listed 'Best First'.
Re^3: how to display descendants in XML with Perl's XML::Twig
by choroba (Cardinal) on Oct 16, 2015 at 13:45 UTC
    I don't understand. Can you post a bit bigger input I can test my code against? Use the <readmore> tags to save readers from excessive scrolling.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Updated the question. I hope this makes more sense. Sorry I cant display a bigger part of the code because of IP
      Edited the question. Hope it makes more sense
        Try
        #!perl use strict; use XML::Twig::XPath; my %record = (); my $twig= new XML::Twig::XPath( twig_handlers => { qr/^Line[1-5]|Author|Publisher|Book|Snap/ => \&line, qr/^C\d+/ => \& rating, }, ); $twig->parsefile( 'book.xml' ); sub line { my ($t,$e) = @_; $record{$e->name} = $e->text; if ($e->name eq 'Publisher'){ report(\%record); %record=(); } } sub rating { my ($t,$e) = @_; my $parent = $e->name.'.'; for ($e->descendants){ if ($_->name =~ /[XY]/){ push @{$record{$parent.$_->name}},$_->text; } } } sub report { my $hr = shift; my @f = qw(Book Snap Line1 Line2 Line3 Line4 Line5); my $line = join '|',@$hr{@f}; for my $key (sort keys %$hr){ if ($key =~ /^C\d+/){ print join '|',$line,$key,@{$hr->{$key}}; print "\n"; } } }
        poj
        It's still not fully clear, but here's what I got from it:

        Output:

        The book of pages||The Beginning|We ceased to exist|Accept it|Now we l +ive|We reject it|C1.X|10.5|3.5|10.5|10.5|10.5|10.5 The book of pages||The Beginning|We ceased to exist|Accept it|Now we l +ive|We reject it|C1.Y|11.4|13.4|11.4|11.4|11.4|11.4 ...
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ