http://www.perlmonks.org?node_id=1029225


in reply to perl & XML: getting last child?

Another way ... :-)

#!/usr/bin/perl -w use strict; use warnings; my $filename = 'library.xml'; use XML::LibXML; my $parser = XML::LibXML->new(); my $doc = $parser->parse_file($filename); print "\nBooks\n"; my @nodes = $doc->findnodes("/library/book[last()]"); foreach my $node (@nodes) { print $node->findvalue( 'title')."\n"; my @authors = $node->findnodes('author'); print "Authors:".scalar(@authors)."\n"; foreach my $auth (@authors) { print $auth->textContent()."\n"; } }
If any of my proposed solutions have minor errors, it's because I don't waste my genius on trivial matters. :-P

Replies are listed 'Best First'.
Re^2: perl & XML: getting last child?
by ambrill (Novice) on Apr 18, 2013 at 12:23 UTC
    This works well. In some cases, the last node is null (or does not exist). How can you print a "0" in those cases? thanks
      If you put some example XML data in a comment, I (or someone else) will almost certaintly work out a way to do it. :-)
      If any of my proposed solutions have minor errors, it's because I don't waste my genius on trivial matters. :-P