Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

XML sample:
<Class ID="E12.Production"> <comment> This class comprises activities that are designed to, and succeed in, +creating one or more new items. It specializes the notion of modification into production. The decisio +n as to whether or not an object is regarded as new is context sensit +ive. Normally, it This entity can be collective: the printing of a thousand books, for e +xample, would normally be considered a single event. An event should also be documented using E81 Transformation if it resu +lts in the destruction of one or more objects and the simultaneous pr +oduction of other </comment> <subClassOf resource="#E11.Modification"/> <subClassOf resource="#E63.Beginning_of_Existence"/> </Class>

My perl code

my $twig = XML::Twig->new( twig_handlers => { Class => \&offer } ); $twig->parsefile('class.xml'); sub offer { my( $t, $offer)= @_; if ($offer->first_child('subClassOf')) { print"is subclass of" .$offer->first_child('subClassOf')->att('resourc +e') } $t->purge; }

My question

How do I get a var set to the second value in the xml tree

Thanks

Replies are listed 'Best First'.
Re: XML twig question
by Tanktalus (Canon) on Mar 01, 2006 at 04:00 UTC

    My guess is you want children which returns an array.

    for my $subclass ($offer->children('subClassOf')) { print "is subclass of " . $subclass->att('resource') . "\n"; }
    That way you have all of them. Of course, children could return an empty list, which means the print statement wouldn't get executed, but that's probably what you want anyway.

    Perl is great for this: rather than doing it the non-idiomatic way you're trying where you go and look for first_child twice, I look for all children at a time and simply loop through them. Chances are, this is exactly what I want: skip the loop if there's nothing, but do everything on each item in the list if there is something.

    Hope that helps.

Re: XML twig question
by runrig (Abbot) on Mar 01, 2006 at 01:59 UTC
    Do you mean the second subClassOf element? Perhaps you want to use next_sibling()? (untested code ahead):
    my $first = $offer->first_child('subClassOf'); my $second = $first->next_sibling('subClassOf');
Re: XML twig question
by diotalevi (Canon) on Mar 01, 2006 at 01:46 UTC

    I read your XML but I couldn't guess what you think "second value in the XML tree" is supposed to be. Show what value you're expecting to get.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

      I am able to get:

      <subClassOf resource="#E11.Modification"/> but how do I get

      <subClassOf resource="#E63.Beginning_of_Existence"/>