The thing is that listing the attributes would not necessary create a unique path to the element. Using the position is the only way that's always garanteed to work. If you look at the example below, you will see that indeed several distinct results have the same complete_path output.

So for your specific case, the solution is to actually write code that does what you want. Or at least to cut-n-paste the code below ;--) Basically it subclasses XML::Twig::Elt to add the complete_xpath method, that does what you want (you could also do it without subclassing, by just calling a function on the element).

#!/usr/bin/perl use strict; use warnings; use XML::Twig; my $xpath_arg= '//*[@keep="1"]'; my $twig= XML::Twig->new( elt_class => 'my_elt')->parse( \*DATA); my $twig_root= $twig->root; my @res = $twig_root->get_xpath($xpath_arg); foreach ( @res ) { print $_->complete_path . " : "; print $_->text . "\n"; } package my_elt; use base 'XML::Twig::Elt'; sub complete_path { my( $elt)= @_; return '/' . join( '/', map { $_->tag_desc } reverse $elt->ancesto +rs_or_self); } sub tag_desc { my( $elt)= @_; my %atts= %{$elt->atts}; my $atts= %atts ? '[' . join( " ", map { qq{$_="$atts{$_}"} } sor +t keys %atts) . ']' : ''; return $elt->tag . $atts; } package main; __DATA__ <doc> <elt att1="1" keep="1"> <elt2 att2="2" keep="1">foo</elt2> <elt2 att2="2" keep="0">bar</elt2> </elt> <elt att1="1"> <elt2 att2="2" keep="0">foo2</elt2> <elt2 att2="2" keep="1">bar2</elt2> </elt> <elt att1="1" keep="1"> <elt2 att2="2" keep="1">foo3</elt2> <elt2 att2="2" keep="1">bar3</elt2> </elt> </doc>

In reply to Re: newbie : XPath - including element attributes by mirod
in thread newbie : XPath - including element attributes by jxh

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.