You can't do that. '/document/header[2]' should trigger an error, [2] is not supported. You will need to call the handler on all headers, and manage the state yourself to see if you have deleted the second one.

This should work, by keeping track taht the second header has already been deleted in a hidden attribute in the parent:

#!/usr/bin/perl use strict; use warnings; use XML::Twig; my $twig_to_del=XML::Twig->new( twig_handlers=>{ #to_delete elements '/document/header'=>\&element_ +delete, }, ) ->parse(\*DATA) ->print; sub element_delete { my ($twig, $element)= @_; my $first_header= $element->prev_sibling( 'header'); if( $first_header && ! $first_header->att( '#header_deleted')) { $element->delete; $first_header->set_att( '#header_deleted' => 1); } } __DATA__ <document> <header>h1</header> <header>h2</header> <header>h3</header> </document>

Of course if you want to delete all headers after the first one, which is more likely, the code is much simpler, you just have to delete any header after the first one:

#!/usr/bin/perl use strict; use warnings; use XML::Twig; my $twig_to_del=XML::Twig->new( twig_handlers=>{ #to_delete elements '/document/header'=> sub { $_- +>delete if $_->prev_sibling( 'header'); }, }, ) ->parse(\*DATA) ->print; __DATA__ <document> <header>h1</header> <header>h2</header> <header>h3</header> </document>

In reply to Re: xml::twig delete element by mirod
in thread xml::twig delete element by Selvakumar

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.