Here is what it would look like:

#!/usr/bin/perl use strict; use warnings; use XML::Twig; my( $ac_n_value, $ai_att_cond)= @ARGV; XML::Twig->new( twig_handlers => { qq{AC[\@n="$ac_n_value"]//AI[$ai_at +t_cond]} => \&print_ai_data }) ->parsefile( "test_thandi.xml"); sub print_ai_data { my( $t, $ai)= @_; print "DESC: ", $ai->first_child( 'Desc')->sprint, "\n", "ID : ", $ai->first_child( 'ID') ->sprint, "\n" ; }

You call this with the value you want for the n attribute of the AC element, and the condition for the AI element:

perl test_thandi CCC '@n=AAA' perl test_thandi CCC '@n="AAA" or @set="y"'

A couple of comments on the code: Perl and XPath strings don't really mix very well: you can use alternate quotes (qq{}) to avoid the collision of perl interpolating quotes and of XPath attribute quotes (or you can use ' instead of " in the XPath expression), but you need to backslash the @ used for attribute conditions in XPath, so it is not interpolated as an array by Perl. An alternate method is to use sprintf to build the XPath expression.

This code loads the entire document in memory, which you may or may not want. There are techniques to avoid this described in the XML::Twig Tutorial.

Also, you need the development version of XML::Twig to be able to run this, you can get it from xmltwig.com.


In reply to Re^3: XML::Twig question by mirod
in thread XML::Twig question by thandi

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.