Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: XML Newbie

by mirod (Canon)
on Nov 16, 2012 at 05:57 UTC ( [id://1004132]=note: print w/replies, xml ) Need Help??


in reply to XML Newbie

An XML::Twig version that does not load the entire XML in memory:

#!/usr/bin/perl use strict; use warnings; use XML::Twig; my $t=XML::Twig->new( start_tag_handlers => { _all_ => \&store_line_number, }, twig_handlers => { _all_ => \&warn_on_empty_elt, }, ); $t->parsefile( "so_line_numbers.xml"); sub store_line_number { my( $twig, $elt)= @_; $elt->set_att( '#line' => $twig->current_line); $elt->parent->set_att( '#not_empty') if $elt->parent; } sub warn_on_empty_elt { my( $twig, $elt)= @_; if( ! $elt->att( '#not_empty') && $elt->text !~ m{\S}) { print $el +t->att( '#line'), "\n"; } $twig->purge; }

The little bit of cleverness here is that the code manages whether an element is empty or not itself, which allows it to purge the twig after each element (otherwise an enclosing element would have no content and trigger the warning).

Replies are listed 'Best First'.
Re^2: XML Newbie
by remiah (Hermit) on Nov 16, 2012 at 09:07 UTC

    Hello mirod.

    I read your post and tried. And found it seems not working good. This prints

    3
    4
    1
    
    And the script is like this. Just added example xml with your script. As you see the DATA, empty tag will be ddd, and eee(line 3,4). And print out of "1" means "gibsonca" tag. I wonder this has relation with parsing of twig, as document says,

    Remember that element handlers are called when the element is CLOSED, so if you have handlers for nested elements the inner handlers will be called first.

    So, as a result of purging inner elements, gibsonca tag is empty for twig, I guess.

    If I comment out purge, it prints line number 3 and 4.

    regards.

    update: Large XML files may have some cluster that may be easy to purge. For example item tag in the below case. Maybe this will print line number of end tag(not as correct as yours), but I would like to purge like this.

      Duh! you need to set #not_empty to a true value. That will teach me to change tested code right before posting it.

      So it should be $elt->parent->set_att( '#not_empty', 1) if $elt->parent;

      regarding the update: in the code I wrote, the twig is purged after each element, that's why you need the #not_empty attribute, because within the twig handler, every single element appears empty, except if it contains text.

        Thanks for reply.

        It works fine.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1004132]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (7)
As of 2024-03-29 08:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found