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";

In reply to Output the content of the last element with a given tag in an XML file by mirod

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.