A couple of times now I came accross situations where I (or someone asking me a question!) had an XML document that included a list of elements, and I wanted to process only the last one of those.
Tree-based processing is pretty lame in such a case, yes, even with XML::Twig! ;--( so here is a solution based on XML::PYX. You need to have XML::PYX intalled to run this, to get pyx and pyxw.
You can then process the output fragment as you want.
#!/bin/perl -w use strict; # this tool outputs the content of the last tag $tag in an xml file # for the file file.xml: # <doc><elt>elt 1</elt><elt>elt 2</elt><foo>elt 3</foo></doc> # last_tag elt file.xml outputs <elt>elt 2</elt> my $USAGE= "$0 <tag> [file(s)]"; my $tag= shift || die $USAGE; my $buffer; # store the current $tag content my $add_to_buffer=0; # 0 -> do not add to buffer, 1-> add open( XML_IN, "pyx @ARGV | ") or die "cannot pyx input file(s): $!"; while( <XML_IN>) { if( m/\($tag$/) { $add_to_buffer= 1; $buffer= ''; } # get start t +ag $buffer.= $_ if( $add_to_buffer); # fill buffer if( m/\)$tag$/) { $add_to_buffer= 0; } # get end tag } close XML_IN; open( XML_OUT, "| pyxw") or die "cannot output buffer: $!"; print XML_OUT $buffer; close XML_OUT; # I need this to output the last line on my linux box with Perl 5.6.1 print "\n";
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |