#!/usr/bin/perl -- use strict; use warnings; use Path::Tiny qw/ path /; use XML::LibXML::Reader; my $deleteme = 'deleteme.xml'; my $xml = q{ 5 Spoke Wheel Reconditioned OEM 123.45 http://foo.example.com http://foo.example.com/foo.jpg sixexample six example 66666.66 http://six.example.com http://six.example.com/foo.jpg two two 222.45 http://two.example.com http://two.example.com/foo.jpg }; path( $deleteme )->spew_raw( $xml ); my $reader = XML::LibXML::Reader->new(location => $deleteme ) or die "cannot read file.xml\n"; my $pattern = XML::LibXML::Pattern->new('/root/product'); while($reader->nextPatternMatch( $pattern) ) { my $node = $reader->copyCurrentNode(!!'deep'); ## get the twig next if ! $node ->hasChildNodes; ## skip empty like closing tags processNode( $node ) ; } $reader->close; undef $reader; path( $deleteme )->remove; exit( 0 ); sub processNode { my( $product ) = @_; my $price = $product->F('./price/text()'); my $name = $product->F('./name/text()'); my $imageurl = $product->F('./imageurl/text()'); print "$price $name $imageurl\n\n"; } sub XML::LibXML::Node::F { my $self = shift; my $xpath = shift; my %prefix = @_; our $XPATHCONTEXT; $XPATHCONTEXT ||= XML::LibXML::XPathContext->new(); while( my( $p, $u ) = each %prefix ){ $XPATHCONTEXT->registerNs( $p, $u ); } $XPATHCONTEXT->findnodes( $xpath, $self ); } __END__ 123.45 5 Spoke Wheel http://foo.example.com/foo.jpg 66666.66 sixexample http://six.example.com/foo.jpg 222.45 two http://two.example.com/foo.jpg