XML-Descent-1.04000755000765000120 011210044534 12654 5ustar00andyadmin000000000000Build.PL000444000765000120 101311210044527 14223 0ustar00andyadmin000000000000XML-Descent-1.04require 5.006001; use strict; use warnings; use Module::Build; use lib 'inc'; use MyBuilder; my $builder = MyBuilder->new( module_name => 'XML::Descent', sign => 1, license => 'perl', dist_author => 'Andy Armstrong ', dist_version_from => 'lib/XML/Descent.pm', requires => { 'Test::More' => 0, 'XML::TokeParser' => 0, 'Test::Differences' => 0, }, add_to_cleanup => ['XML-Descent-*'], ); $builder->create_build_script(); Changes000444000765000120 157611210044527 14240 0ustar00andyadmin000000000000XML-Descent-1.04Revision history for XML-Descent 0.0.1 2006-11-22 Initial release. 0.0.2 2006-12-13 Removed orphaned reference to 'stash' in documentation 0.0.3 2007-02-23 Added machine readable license to META.yml 0.0.4 2007-02-23 Removed silly tutorial module. Will write some runnable examples instead. 0.10 2007-11-22 Removed dependencies on Class::Std, version.pm 0.11 2007-11-22 Removed garbage at eof. 1.00 2009-03-10 Tidy up documentation. Allow on to accept multiple handler specs. 1.01 2009-03-10 Fix inherit and test. Implement before/after hooks. Implement scope_handlers, all_handlers. 1.02 2009-05-14 Make C round trip entities correctly. 1.03 2009-05-17 Allow element paths to be supplied to C. 1.04 2009-05-29 Move to GitHub MANIFEST000444000765000120 37211210044527 14047 0ustar00andyadmin000000000000XML-Descent-1.04Build.PL Changes inc/MyBuilder.pm lib/XML/Descent.pm Makefile.PL MANIFEST META.yml README t/00.load.t t/01.parse.t t/02.inherit.t t/03.text.t t/04.mark.t t/05.path.t t/lib/My/Cases.pm t/pod-coverage.t t/pod.t SIGNATURE Added here by Module::Build META.yml000444000765000120 110711210044527 14204 0ustar00andyadmin000000000000XML-Descent-1.04--- name: XML-Descent version: 1.04 author: - 'Andy Armstrong ' abstract: Recursive descent XML parsing license: perl resources: bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=XML-Descent license: http://dev.perl.org/licenses/ repository: git://github.com/AndyA/XML--Descent.git requires: Test::Differences: 0 Test::More: 0 XML::TokeParser: 0 provides: XML::Descent: file: lib/XML/Descent.pm version: 1.04 generated_by: Module::Build version 0.33 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 Makefile.PL000444000765000120 140111210044527 14702 0ustar00andyadmin000000000000XML-Descent-1.04require 5.006001; use strict; use warnings; use ExtUtils::MakeMaker; WriteMakefile( ( MM->can( 'signature_target' ) ? ( SIGN => 1 ) : () ), license( 'perl' ), NAME => 'XML::Descent', AUTHOR => 'Andy Armstrong ', VERSION_FROM => 'lib/XML/Descent.pm', ABSTRACT_FROM => 'lib/XML/Descent.pm', PL_FILES => {}, PREREQ_PM => { 'Test::More' => 0, 'XML::TokeParser' => 0, 'Test::Differences' => 0, }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'XML-Descent-*' }, ); sub license { my $lic = shift; local $^W = 0; # Silence warning about non-numeric version return unless $ExtUtils::MakeMaker::VERSION >= '6.31'; return ( LICENSE => $lic ); } README000444000765000120 101211210044527 13606 0ustar00andyadmin000000000000XML-Descent-1.04XML-Descent version 1.04 INSTALLATION To install this module, run the following commands: perl Makefile.PL make make test make install Alternatively, to install with Module::Build, you can use the following commands: perl Build.PL ./Build ./Build test ./Build install DEPENDENCIES XML::TokeParser Class::Std COPYRIGHT AND LICENCE Copyright (C) 2006-2009, Andy Armstrong This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. SIGNATURE000644000765000120 326711210044534 14230 0ustar00andyadmin000000000000XML-Descent-1.04This file contains message digests of all files listed in MANIFEST, signed via the Module::Signature module, version 0.55. To verify the content in this distribution, first make sure you have Module::Signature installed, then type: % cpansign -v It will check each file's integrity, as well as the signature's validity. If "==> Signature verified OK! <==" is not displayed, the distribution may already have been compromised, and you should not run its Makefile.PL or Build.PL. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 SHA1 8e67d16a2d386e4672f66aaee60aad1554457aa0 Build.PL SHA1 1e441465df96a68d5ddf1711f3c857954d8c5efa Changes SHA1 78cf3413b0c799dafef8ffc0f844c74df037d92e MANIFEST SHA1 30906a95fe7ada8835051dfb98c939d4cd416940 META.yml SHA1 0376fb9c568d20ca8030d9cd46e22377fef2a00d Makefile.PL SHA1 1426010a12fa2cf207cc923205c6b19bde62ea3f README SHA1 8c97bbeb63b586ee9c722313c2ad7858e32ff52c inc/MyBuilder.pm SHA1 ca098203efe42eb796ac8fc81ea5e6d59cad8f6d lib/XML/Descent.pm SHA1 bc499792821d7787b40a2f19bfd445b654950288 t/00.load.t SHA1 2eb261450af56292f6092b8c8aa28aa41f959d7f t/01.parse.t SHA1 97998afef72bba0665dcab78246cb5ef3061b4e3 t/02.inherit.t SHA1 de77292fdf62ff990d9768e0e19e38efb0abdf88 t/03.text.t SHA1 8a1a14e2b5d771a2c2ab081ba445c601135cc9c6 t/04.mark.t SHA1 2055ae54ed7ebaf14554c42f00851af83a070eb8 t/05.path.t SHA1 5114f2ad476468fb71000b4114e558547bf23213 t/lib/My/Cases.pm SHA1 aeaa691851a425f07ab6a8d4f825e2ad9d92b8ee t/pod-coverage.t SHA1 0190346d7072d458c8a10a45c19f86db641dcc48 t/pod.t -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iEYEARECAAYFAkogSVcACgkQwoknRJZQnCGkEQCeKDzBa5RlJHu/UihgnTfL2v5T YZoAniwhbqZM3vgwbp9KG3D3mkCfXV3w =4sXC -----END PGP SIGNATURE----- inc000755000765000120 011210044527 13350 5ustar00andyadmin000000000000XML-Descent-1.04MyBuilder.pm000444000765000120 353111210044527 15741 0ustar00andyadmin000000000000XML-Descent-1.04/incpackage MyBuilder; use base qw( Module::Build ); sub create_build_script { my ( $self, @args ) = @_; $self->_auto_mm; return $self->SUPER::create_build_script( @args ); } sub _auto_mm { my $self = shift; my $mm = $self->meta_merge; my @meta = qw( homepage bugtracker MailingList repository ); for my $meta ( @meta ) { next if exists $mm->{resources}{$meta}; my $auto = "_auto_$meta"; next unless $self->can( $auto ); my $av = $self->$auto(); $mm->{resources}{$meta} = $av if defined $av; } $self->meta_merge( $mm ); } sub _auto_repository { my $self = shift; if ( -d '.svn' ) { my $info = `svn info .`; return $1 if $info =~ /^URL:\s+(.+)$/m; } elsif ( -d '.git' ) { my $info = `git remote -v`; return unless $info =~ /^origin\s+(.+)$/m; my $url = $1; # Special case: patch up github URLs $url =~ s!^git\@github\.com:!git://github.com/!; return $url; } return; } sub _auto_bugtracker { 'http://rt.cpan.org/NoAuth/Bugs.html?Dist=' . shift->dist_name; } sub ACTION_testauthor { my $self = shift; $self->test_files( 'xt/author' ); $self->ACTION_test; } sub ACTION_critic { exec qw( perlcritic -1 -q -profile perlcriticrc lib/ ), glob 't/*.t'; } sub ACTION_tags { exec( qw( ctags -f tags --recurse --totals --exclude=blib --exclude=.svn --exclude='*~' --languages=Perl t/ lib/ ) ); } sub ACTION_tidy { my $self = shift; my @extra = qw( Build.PL ); my %found_files = map { %$_ } $self->find_pm_files, $self->_find_file_by_type( 'pm', 't' ), $self->_find_file_by_type( 'pm', 'inc' ), $self->_find_file_by_type( 't', 't' ); my @files = ( keys %found_files, map { $self->localize_file_path( $_ ) } @extra ); for my $file ( @files ) { system 'perltidy', '-b', $file; unlink "$file.bak" if $? == 0; } } 1; lib000755000765000120 011210044527 13345 5ustar00andyadmin000000000000XML-Descent-1.04XML000755000765000120 011210044527 14005 5ustar00andyadmin000000000000XML-Descent-1.04/libDescent.pm000444000765000120 4130611210044527 16111 0ustar00andyadmin000000000000XML-Descent-1.04/lib/XMLpackage XML::Descent; use warnings; use strict; use Carp; use XML::TokeParser; =head1 NAME XML::Descent - Recursive descent XML parsing =head1 VERSION This document describes XML::Descent version 1.04 =head1 SYNOPSIS use XML::Descent; # Create parser my $p = XML::Descent->new( { Input => \$xml } ); # Setup handlers $p->on( folder => sub { my ( $elem, $attr ) = @_; $p->on( url => sub { my ( $elem, $attr ) = @_; my $link = { name => $attr->{name}, url => $p->text }; } ); my $folder = $p->walk; $folder->{name} = $attr->{name}; } ); # Parse my $res = $p->walk; =head1 DESCRIPTION The conventional models for parsing XML are either DOM (a data structure representing the entire document tree is created) or SAX (callbacks are issued for each element in the XML). XML grammar is recursive - so it's nice to be able to write recursive parsers for it. XML::Descent allows such parsers to be created. Typically a new XML::Descent is created and handlers are defined for elements we're interested in my $p = XML::Descent->new( { Input => \$xml } ); $p->on( link => sub { my ( $elem, $attr ) = @_; print "Found link: ", $attr->{url}, "\n"; $p->walk; # recurse } ); $p->walk; # parse A handler provides a convenient lexical scope that lasts until the closing tag of the element that triggered the handler is reached. When called at the top level the parsing methods walk, text and xml parse the whole XML document. When called recursively within a handler they parse the portion of the document nested inside node that triggered the handler. New handlers may be defined within a handler and their scope will be limited to the XML inside the node that triggered the handler. =cut our $VERSION = '1.04'; =head1 INTERFACE =head2 C Create a new XML::Descent. Options are supplied has a hash reference. The only option recognised directly by XML::Descent is C which should be reference to the object that provides the XML source. Any value that can be passed as the first argument to C<< XML::TokeParser->new >> is allowed. The remaining options are passed directly to C. Consult that module's documentation for more details. =cut sub new { my $class = shift; my %args = (); my @opt = (); for my $arg ( @_ ) { if ( 'HASH' eq ref $arg ) { %args = ( %args, %$arg ); } else { push @opt, $arg; } } croak "Expected a number of name => value pairs" if @opt % 2; %args = ( %args, @opt ); my $parser = XML::TokeParser->new( delete $args{Input} || croak( "No Input arg" ), %args ) || croak( "Failed to create XML::TokeParser" ); return bless { parser => $parser, context => { parent => undef, rules => {}, obj => undef }, token => undef, path => [], }, $class; } sub _get_rule_handler { my ( $self, $tos, $elem ) = @_; croak "It is not possible to register an explicit handler for '*'" if '*' eq $elem; while ( $tos ) { if ( my $h = $tos->{rules}{$elem} || $tos->{rules}{'*'} ) { return $h; } $tos = $tos->{parent}; } return; } sub _depth { scalar @{ shift->{path} } } =head2 C Parse part of the XML document tree triggering any handlers that correspond with elements it contains. When called recursively within a handler C visits all the elements below the element that triggered the handler and then returns. =cut sub walk { my $self = shift; TOKEN: while ( my $tok = $self->get_token ) { if ( $tok->[0] eq 'S' ) { my $tos = $self->{context}; my $handler = $self->_get_rule_handler( $tos, $tok->[1] ); if ( defined $handler ) { my $stopat = $self->_depth; # Push context $self->{context} = { parent => $tos, stopat => $stopat, obj => $tos->{obj} }; # Call handler $handler->( $tok->[1], $tok->[2], $tos->{obj} ); # If handler didn't recursively parse the content of # this node we need to discard it. 1 while $self->_depth >= $stopat && ( $tok = $self->get_token ); # Pop context $self->{context} = $tos; } else { $self->walk; } } elsif ( $tok->[0] eq 'E' ) { last TOKEN; } } } =head2 C Register a handler to be called when the named element is encountered. Multiple element names may be supplied as an array reference. Multiple handlers may be registered with one call to C by supplying a number of element, handler pairs. Calling C within a handler defines a nested local handler whose scope is limited to the containing element. Handlers are called with three arguments: the name of the element that triggered the handler, a hash of the element's attributes and a user defined context value - see C for more about that. For example: $p = XML::Descent->new( { Input => \$some_xml } ); # Global handler - trigger anywhere an tag is found $p->on( options => sub { my ( $elem, $attr, $ctx ) = @_; # Define a nested handler for elements that only # applies within the handler. $p->on( name => sub { my ( $elem, $attr, $ctx ) = @_; # Get the inner text of the name element my $name = $p->text; print "Name: $name\n"; } ); # Recursively walk elements inside triggering # any handlers $p->walk; } ); # Start parsing $p->walk; A handler may call one of the parsing methods (C, C, C or C) to consume any nested XML before returning. If none of the parsing methods are called nested XML is automatically discarded so that the parser can properly move past the current element. Nested handlers temporarily override another handler with the same name. A handler named '*' will trigger for all elements for which there is no explicit handler. A nested '*' handler hides all handlers defined in containing scopes. As a shorthand you may specify a path to a nested element: $p->on( 'a/b/c' => sub { print "Woo!\n"; })->walk; That's equivalent to: $p->on( a => sub { $p->on( b => sub { $p->on( c => sub { print "Woo!\n"; })->walk; })->walk; })->walk; Note that this shorthand only applies to C - not to other methods that accept element names. =cut sub on { my $self = shift; croak "Please supply a number of path => handler pairs" if @_ % 2; while ( my ( $spec, $cb ) = splice @_, 0, 2 ) { $spec = [$spec] unless ref $spec eq 'ARRAY'; for my $el ( @$spec ) { my ( $name, $tail ) = split /\//, $el, 2; if ( defined $tail ) { $self->{context}{rules}{$name} = sub { $self->on( $tail => $cb )->walk; }; } else { $self->{context}{rules}{$el} = $cb; } } } return $self; } =head2 C Inherit handlers from the containing scope. Typically used to import handlers that would otherwise be masked by a catch all '*' handler. $p->on( 'a' => sub { my ( $elem, $attr, $ctx ) = @_; my $link = $attr->{href} || ''; my $text = $p->text; print "Link: $text ($link)\n"; } ); $p->on( 'special' => sub { my ( $elem, $attr, $ctx ) = @_; # Within we want to handle all # tags apart from by printing them out $p->on( '*' => sub { my ( $elem, $attr, $ctx ) = @_; print "Found: $elem\n"; } ); # Get the handler for from our containing # scope. $p->inherit( 'a' ); $p->walk; } ); The inherited handler is the handler that would have applied in the containing scope for an element with the given name. For example: $p->on( '*' => sub { print "Whatever\n"; $p->walk; } ); $p->on( 'interesting' => sub { # Inherits the default 'Whatever' handler because that's the # handler that would have been called for in the # containing scope $p->inherit( 'frob' ); # Handle everything else ourselves #p->on('*', sub { $p->walk; }); } ); =cut sub inherit { my $self = shift; my ( $path ) = @_; $path = [$path] unless ref $path eq 'ARRAY'; my $par = $self->{context}{parent}; $self->on( $_, $self->_get_rule_handler( $par, $_ ) ) for @$path; return $self; } sub _filter { my ( $self, $mk_wrapper ) = splice @_, 0, 2; croak "Please supply a number of path => handler pairs" if @_ % 2; my $context = $self->{context}; while ( my ( $path, $cb ) = splice @_, 0, 2 ) { $path = [$path] unless ref $path eq 'ARRAY'; for my $elem ( @$path ) { my $h = $self->_get_rule_handler( $context, $elem ) or croak "No existing handler for $elem"; $self->{context}{rules}{$elem} = $mk_wrapper->( $h, $cb ); } } return $self; } =head2 C Register a handler to be called before the existing handler for an element. As with C multiple elements may be targetted by providing an array ref. =cut sub before { return shift->_filter( sub { my ( $h, $cb ) = @_; sub { $cb->( @_ ); $h->( @_ ) } }, @_ ); } =head2 C Register a handler to be called after the existing handler for an element. As with C multiple elements may be targetted by providing an array ref. =cut sub after { return shift->_filter( sub { my ( $h, $cb ) = @_; sub { $h->( @_ ); $cb->( @_ ) } }, @_ ); } =head2 C Every time a handler is called a new scope is created for it. This allows nested handlers to be defined. The current scope contains a user context variable which can be used, for example, to keep track of an object that is being filled with values parsed from the XML. The context value is inherited from the parent scope but may be overridden locally. For example: my $root = {}; # Set the outermost context $p->context( $root ); # Handle HTML links /anywhere/ $p->on( 'a' => sub { my ( $elem, $attr, $ctx ) = @_; my $link = { href => $attr->{href}, text => $p->text }; push @{ $ctx->{links} }, $link; } ); # Links in the body are stored in a nested # object. $p->on( 'body' => sub { my ( $elem, $attr, $ctx ) = @_; my $body = {}; # Set the context $p->context( $body ); $p->walk; $ctx->{body} = $body; } ); $p->walk; Note that the handler for tags stores its results in the current context object - whatever that happens to be. That means that outside of any tag links will be stored in C<$root> but within a they will be stored in a nested object (C<< $root->{body} >>). The handler itself need know nothing of this. With no parameter C returns the current context. The current context is also passed as the third argument to handlers. =cut sub context { my $self = shift; $self->{context}->{obj} = shift if @_; return $self->{context}{obj}; } =head2 C Return any text contained within the current element. XML markup is discarded. =cut sub text { my $self = shift; my @txt = (); TOKEN: while ( my $tok = $self->get_token ) { if ( $tok->[0] eq 'S' ) { push @txt, $self->text; } elsif ( $tok->[0] eq 'E' ) { last TOKEN; } elsif ( $tok->[0] eq 'T' ) { push @txt, $tok->[1]; } } return join '', @txt; } =head2 C Return the unparsed inner XML of the current element. For example: $p->on( 'item' => sub { my ( $elem, $attr, $ctx ) = @_; my $item_source = $p->xml; print "Item: $item_source\n"; } ); If contains XHTML (for example) the above handler would correctly capture it without recursively parsing any elements it contains. Parsing This is the first story. This is another story. would print Item: This is the first story. Item: This is another story. =cut sub xml { my $self = shift; my @xml = (); TOKEN: while ( my $tok = $self->get_token ) { if ( $tok->[0] eq 'S' ) { push @xml, $tok->[4], $self->xml, $self->{token}->[2]; } elsif ( $tok->[0] eq 'E' ) { last TOKEN; } elsif ( $tok->[0] eq 'T' || $tok->[0] eq 'C' ) { push @xml, $tok->[2]; } elsif ( $tok->[0] eq 'PI' ) { push @xml, $tok->[3]; } else { die "Unhandled token type: $tok->[0]"; } } return join '', @xml; } =head2 C Called within a handler returns the path that leads to the current element. For example: $p->on( 'here' => sub { my ( $elem, $attr, $ctx ) = @_; print "I am here: ", $p->get_path, "\n"; $p->walk; } ); would, if applied to this XML print I am here: /outer/inner/here I am here: /outer/here =cut sub get_path { '/' . join '/', @{ shift->{path} } } =head2 C XML::Descent is built on C which splits an XML document into a stream of tokens representing start tags, end tags, literal text, comment and processing instructions. Within an element C returns the same stream of tokens that C would produce. Returns C once all the tokens contained within the current element have been read (i.e. it's impossible to read past the end of the enclosed XML). =cut sub get_token { my $self = shift; my $p = $self->{parser}; my $tok = $self->{token} = $p->get_token; if ( defined( $tok ) ) { if ( $tok->[0] eq 'S' ) { push @{ $self->{path} }, $tok->[1]; } elsif ( $tok->[0] eq 'E' ) { my $tos = pop @{ $self->{path} }; die "$tos <> $tok->[1]" unless $tos eq $tok->[1]; } } my $stopat = $self->{context}{stopat}; return if defined $stopat && $self->_depth < $stopat; return $tok; } =head2 C Get a list of all handlers that are registered locally to the current scope. The returned list won't include '*' if a wildcard handler has been registered. =cut sub scope_handlers { sort grep { $_ ne '*' } keys %{ shift->{context}{rules} || {} }; } =head2 C Get a list of all registered handlers in all scopes. The returned list won't include the '*' wildcard handler. =cut sub all_handlers { my $self = shift; my %seen = (); my @h = (); my $tos = $self->{context}; while ( $tos ) { push @h, grep { !$seen{$_}++ } grep { $_ ne '*' } keys %{ $tos->{rules} || {} }; $tos = $tos->{parent}; } return sort @h; } 1; __END__ =head1 SEE ALSO L, L, L. =head1 BUGS AND LIMITATIONS XML::Descent uses C to do the actual parsing. XML::TokeParser can only return start tags, end tags, raw text and processing instructions. As a result C called at the root of an XML document will exclude any declaration. No bugs have been reported. Please report any bugs or feature requests to C, or through the web interface at L. =head1 AUTHOR Andy Armstrong C<< >> =head1 LICENCE AND COPYRIGHT Copyright (c) 2006-2009, Andy Armstrong C<< >>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. t000755000765000120 011210044527 13042 5ustar00andyadmin000000000000XML-Descent-1.0400.load.t000444000765000120 17211210044527 14501 0ustar00andyadmin000000000000XML-Descent-1.04/tuse Test::More tests => 1; BEGIN { use_ok( 'XML::Descent' ); } diag( "Testing XML::Descent $XML::Descent::VERSION" ); 01.parse.t000444000765000120 1503711210044527 14743 0ustar00andyadmin000000000000XML-Descent-1.04/tuse Test::More tests => 12; use Data::Dumper; BEGIN { use_ok( 'XML::Descent' ); } my $xml = < http://hexten.net/ http://www.koders.com/ http://search.cpan.org/ http://perldoc.perl.org/ http://www.ruby-lang.org/ Frog fleening The body text is just HTML. http://cpan.hexten.net/ This text is ignored This has a handler which doesn't recursively parse the contents This is tokenised. EOX # Trailing newline causes problems chomp $xml; #### Test xml() returns original source my $p1 = XML::Descent->new( { Input => \$xml } ); my $o1 = $p1->xml(); is( $o1, $xml, 'unparsed XML' ); #### Test text() returns all text ( my $text = $xml ) =~ s/<[^>]+>//g; my $p2 = XML::Descent->new( { Input => \$xml } ); my $o2 = $p2->text(); is( $o2, $text, 'extracted text' ); #### Global extract tag contents my @furls = $xml =~ />(http:.+?)new( { Input => \$xml } ); my @gurls = (); $p3->on( url => sub { push @gurls, $p3->text(); } ); $p3->walk(); is_deeply( \@gurls, \@furls, 'extract urls' ); #### Get all elements my @felem = $xml =~ /<(\w+)/g; my $p4 = XML::Descent->new( { Input => \$xml } ); my @gelem = (); $p4->on( '*' => sub { my ( $elem, $attr ) = @_; push @gelem, $elem; $p4->walk(); } ); $p4->walk(); is_deeply( \@gelem, \@felem, 'all elements' ); #### Global extract attribute my @fnames = $xml =~ /name=\"(.*?)\"/g; my $p5 = XML::Descent->new( { Input => \$xml } ); my @gnames = (); $p5->on( '*' => sub { my ( $elem, $attr ) = @_; push @gnames, $attr->{name} if exists $attr->{name}; $p5->walk(); } ); $p5->walk(); is_deeply( \@gnames, \@fnames, 'extracted attributes' ); #### Extract inner XML my @fmeta = $xml =~ m{(.*?)}sm; my $gmeta = undef; my $p6 = XML::Descent->new( { Input => \$xml } ); $p6->on( meta => sub { $gmeta = $p6->xml(); } ); $p6->walk(); is( $gmeta, $fmeta[0], 'extract inner XML' ); #### Extract inner text ( my $ftext = $fmeta[0] ) =~ s/<.+?>//g; my $gtext = undef; my $p7 = XML::Descent->new( { Input => \$xml } ); $p7->on( meta => sub { $gtext = $p7->text(); } ); $p7->walk(); is( $gtext, $ftext, 'extract inner text' ); #### Test get_tok my $ftag = bless( [ 'E', 'url', '' ], 'XML::TokeParser::Token' ); my $p8 = XML::Descent->new( { Input => \$xml } ); my $gtag = undef; $p8->on( favourites => sub { TOK: while ( my $tok = $p8->get_token() ) { if ( $tok->[0] eq 'E' ) { $gtag = $tok; last TOK; } } } ); my $gmeta2 = 0; $p8->on( meta => sub { $gmeta2++; } ); $p8->walk(); is_deeply( $gtag, $ftag, 'get_token' ); is( $gmeta2, 1, 'found meta' ); #### Test paths my @path = (); my @fpath = (); while ( $xml =~ m{<(/?[a-z]+)}g ) { my $tag = $1; if ( $tag =~ m{^/} ) { pop @path; } else { push @path, $tag; push @fpath, '/' . join( '/', @path ); } } my @gpath = (); my $p9 = XML::Descent->new( { Input => \$xml } ); $p9->on( '*' => sub { push @gpath, $p9->get_path(); $p9->walk(); } ); $p9->walk(); is_deeply( \@gpath, \@fpath, 'get_path()' ); #### Test context my $p10 = XML::Descent->new( { Input => \$xml } ); my $root = {}; $p10->context( $root ); $p10->on( '*' => sub { my ( $elem, $attr, $ctx ) = @_; my $obj = { %{$attr} }; # Keep attributes $p10->context( $obj ); $p10->walk(); # Save results in caller's context push @{ $ctx->{$elem} }, $obj; } ); # Leaf elements -> save text $p10->on( [ 'url', 'title', 'ignored', 'handled' ], sub { my ( $elem, $attr, $ctx ) = @_; push @{ $ctx->{$elem} }, { %{$attr}, inner_text => $p10->text() }; } ); $p10->on( [ 'body', 'tokenised' ] => sub { my ( $elem, $attr, $ctx ) = @_; push @{ $ctx->{$elem} }, { %{$attr}, inner_text => $p10->xml() }; } ); $p10->walk(); $fstruc = { 'config' => [ { 'favourites' => [ { 'folder' => [ { 'url' => [ { 'name' => 'Hexten', 'inner_text' => 'http://hexten.net/' } ], 'name' => 'Me' }, { 'url' => [ { 'name' => 'Source code search', 'inner_text' => 'http://www.koders.com/' } ], 'name' => 'Programming', 'folder' => [ { 'url' => [ { 'name' => 'CPAN Search', 'inner_text' => 'http://search.cpan.org/' }, { 'name' => 'Perl Documentation', 'inner_text' => 'http://perldoc.perl.org/' } ], 'name' => 'Perl' }, { 'url' => [ { 'name' => 'Ruby Home', 'inner_text' => 'http://www.ruby-lang.org/' } ], 'name' => 'Ruby' } ] } ] } ], 'meta' => [ { 'body' => [ { 'inner_text' => 'The body text is just HTML.' } ], 'handled' => [ { 'inner_text' => 'This has a handler which doesn\'t recursively parse the contents' } ], 'url' => [ { 'inner_text' => 'http://cpan.hexten.net/' } ], 'title' => [ { 'inner_text' => 'Frog fleening' } ], 'tokenised' => [ { 'inner_text' => 'This is tokenised.' } ], 'ignored' => [ { 'inner_text' => 'This text is ignored' } ] } ] } ] }; is_deeply( $root, $fstruc, 'context' ); 02.inherit.t000444000765000120 615411210044527 15254 0ustar00andyadmin000000000000XML-Descent-1.04/t#!perl # vim:ts=2:sw=2:et:ft=perl use strict; use warnings; use XML::Descent; use Data::Dumper; use Test::More tests => 4; use Test::Differences; my $td = test_data( do { local $/; } ); # inherit { ok my $p = XML::Descent->new( Input => \$td->{t1} ); my @got = (); $p->on( link => sub { my ( $elem, $attr, $ctx ) = @_; push @got, [ $p->get_path, $attr ]; }, name => sub { my ( $elem, $attr, $ctx ) = @_; push @got, [ $p->get_path, $attr ]; }, nested => sub { my ( $elem, $attr, $ctx ) = @_; $p->on( '*' => sub { my ( $elem, $attr, $ctx ) = @_; push @got, [ '*', $p->get_path, $attr ]; } )->inherit( 'name' )->walk; }, )->walk; my @expect = ( [ '/root/link', { 'href' => 'http://hexten.net/' } ], [ '/root/name', {} ], [ '*', '/root/nested/link', { 'href' => 'http://perl.org/' } ], [ '/root/nested/name', {} ], [ '*', '/root/nested/froob', { 'id' => '2' } ] ); unless ( eq_or_diff \@got, \@expect, 'inherit' ) { diag Dumper( \@got ); } } # before/after { ok my $p = XML::Descent->new( Input => \$td->{t1} ); my @got = (); $p->on( link => sub { my ( $elem, $attr, $ctx ) = @_; push @got, [ $p->get_path, $attr ]; }, name => sub { my ( $elem, $attr, $ctx ) = @_; push @got, [ $p->get_path, $attr ]; }, nested => sub { my ( $elem, $attr, $ctx ) = @_; $p->before( link => sub { push @got, 'before link' } ); $p->after( name => sub { push @got, 'after name' } ); $p->on( froob => sub { my ( $elem, $attr, $ctx ) = @_; push @got, [ $p->get_path, $attr ]; } ); $p->after( froob => sub { push @got, 'after froob' } ); $p->before( froob => sub { push @got, 'before froob' } ); push @got, { scope_handlers => [ $p->scope_handlers ], all_handlers => [ $p->all_handlers ] }; $p->walk; }, )->walk; my @expect = ( [ '/root/link', { 'href' => 'http://hexten.net/' } ], [ '/root/name', {} ], { 'all_handlers' => [ 'froob', 'link', 'name', 'nested' ], 'scope_handlers' => [ 'froob', 'link', 'name' ] }, 'before link', [ '/root/nested/link', { 'href' => 'http://perl.org/' } ], [ '/root/nested/name', {} ], 'after name', 'before froob', [ '/root/nested/froob', { 'id' => '2' } ], 'after froob' ); unless ( eq_or_diff \@got, \@expect, 'before/after' ) { diag Dumper( \@got ); } } sub test_data { my $xml = shift; my $td = {}; my $p = XML::Descent->new( Input => \$xml ); $p->on( test => sub { my ( $elem, $attr, $ctx ) = @_; $td->{ $attr->{id} } = $p->xml; } )->walk; return $td; } __DATA__ Hexten Horse Fingers Perl Providence 03.text.t000444000765000120 53011210044527 14547 0ustar00andyadmin000000000000XML-Descent-1.04/t#!perl use strict; use warnings; use Test::More tests => 1; use XML::Descent; { my $text = "This & that"; my $xml = "

$text

"; my $p = XML::Descent->new( { Input => \$xml } ); my $got; $p->on( p => sub { $got = $p->xml; } )->walk; is $got, $text, 'round trip OK'; } # vim:ts=2:sw=2:et:ft=perl 04.mark.t000444000765000120 146311210044527 14544 0ustar00andyadmin000000000000XML-Descent-1.04/t#!perl use strict; use warnings; use XML::Descent; use Test::More; plan skip_all => 'mark/rewind not done yet'; plan tests => 4; { my $inner = "Foo"; my $middle = "

$inner

"; my $outer = "$middle"; my $p = XML::Descent->new( { Input => \$outer } ); $p->on( body => sub { my $got_p = 0; $p->on( p => sub { $got_p++; my $got_b = 0; $p->on( b => sub { $got_b++ } ); $p->mark->walk; my $txt_b = $p->rewind->text; is $got_b, 1, 'inner walk'; is $txt_b, 'Foo', 'inner text'; } ); $p->mark->walk; my $xml_p = $p->rewind->xml; is $got_p, 1, 'middle walk'; is $xml_p, $middle, 'middle text'; } ); $p->walk; } # vim:ts=2:sw=2:et:ft=perl 05.path.t000444000765000120 173011210044527 14544 0ustar00andyadmin000000000000XML-Descent-1.04/t#!perl # vim:ts=2:sw=2:et:ft=perl use strict; use warnings; use lib qw( t/lib ); use My::Cases; use Test::More; use XML::Descent; my $source = load_cases; my @case = ( { name => 'Simple, deep', xml => 'abcde', paths => ['a/b/c/d/e'], expect => ['Whoop!'], } ); plan tests => @case * 1; for my $case ( @case ) { my $name = $case->{name}; my $xml = $source->{ $case->{xml} }; my $p = XML::Descent->new( { Input => \$xml } ); my @got = (); for my $path ( @{ $case->{paths} } ) { $p->on( $path => sub { push @got, tidy( $p->text ); } )->walk; } is_deeply [@got], $case->{expect}, 'parse'; } sub tidy { my $src = shift; $src =~ s/^\s+//; $src =~ s/\s+$//; $src =~ s/\s+/ /g; return $src; } __DATA__ Whoop! pod-coverage.t000444000765000120 36211210044527 15720 0ustar00andyadmin000000000000XML-Descent-1.04/t#!perl -T use Test::More; eval "use Test::Pod::Coverage 1.04"; plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@; all_pod_coverage_ok( { private => [ qr{^BUILD|DEMOLISH|AUTOMETHOD|START$}, qr{^_} ] } ); pod.t000444000765000120 21411210044527 14123 0ustar00andyadmin000000000000XML-Descent-1.04/t#!perl -T use Test::More; eval "use Test::Pod 1.14"; plan skip_all => "Test::Pod 1.14 required for testing POD" if $@; all_pod_files_ok(); lib000755000765000120 011210044527 13610 5ustar00andyadmin000000000000XML-Descent-1.04/tMy000755000765000120 011210044527 14175 5ustar00andyadmin000000000000XML-Descent-1.04/t/libCases.pm000444000765000120 131411210044527 15725 0ustar00andyadmin000000000000XML-Descent-1.04/t/lib/Mypackage My::Cases; use strict; use warnings; use Carp; use XML::Descent; use base qw( Exporter ); our @EXPORT = our @EXPORT_OK = qw( load_cases ); =head1 NAME My::Cases - Load test cases from a chunk of data =head2 C Load cases from a filehandle. =cut sub load_cases { my $fh = shift || \*main::DATA; my $cases = {}; my $p = XML::Descent->new( { Input => $fh } ); $p->on( cases => sub { $p->on( case => sub { my ( $el, $at ) = @_; croak "Missing name on case" unless exists $at->{name}; $cases->{ $at->{name} } = $p->xml; } )->walk; } )->walk; return $cases; } 1; # vim:ts=2:sw=2:sts=2:et:ft=perl