simple XML question for perl - how to retrieve specific elements

Posted by Jeff on Stack Overflow See other posts from Stack Overflow or by Jeff
Published on 2011-01-10T04:51:59Z Indexed on 2011/01/10 5:53 UTC
Read the original article Hit count: 231

Filed under:
|

I'm trying to figure out how to loop through XML but I've read a lot and I'm still getting stuck. Here's the info:

I'm using the wordnik api to retrieve XML with XML::Simple:

 $content = get($url);
 $r = $xml->XMLin("$content");

The actual XML looks like this:

<definitions>
-
<definition sequence="0" id="0">
-
<text>
To withdraw one's support or help from, especially in spite of duty, allegiance, or responsibility; desert:  abandon a friend in trouble. 
</text>
<headword>abandon</headword>
<partOfSpeech>verb-transitive</partOfSpeech>
</definition>
-
<definition sequence="1" id="0">
-
<text>
To give up by leaving or ceasing to operate or inhabit, especially as a result of danger or other impending threat:  abandoned the ship. 
</text>
<headword>abandon</headword>
<partOfSpeech>verb-transitive</partOfSpeech>
</definition>
-
<definition sequence="2" id="0">
-
<text>
To surrender one's claim to, right to, or interest in; give up entirely. See Synonyms at relinquish.
</text>
<headword>abandon</headword>
<partOfSpeech>verb-transitive</partOfSpeech>
</definition>
-
<definition sequence="3" id="0">

...

What I want is simply the FIRST definition's part of speech. I'm using this code but it's getting the LAST definition's POS:

    if($r->{definition}->{0}->{partOfSpeech}) {
      $pos = $r->{definition}->{0}->{partOfSpeech};
     }
else { $pos = $r->{definition}->{partOfSpeech}; }

I am pretty embarrassed by this since I know there's an obviously better way to do it. I would love to get something as simple as this working so I could more generally loop through the elements. BUt it just isn't working for me (no idea what to reference). I've tried many variations of the following - this is just my last attempt:

 while (my ($k, $v) = each %{$r->{definitions}->{definition}[0]->{sequence}->{partOfSpeech}}) {
  $v =~ s/'/'"'"'/g;
  $v = "'$v'";
  print "export $k=$v\n";
 }

Lastly, when I do "print Dumper($r)" it gives me this:

$VAR1 = {
          'definition' => {
                          '0' => {
                                 'partOfSpeech' => 'noun',
                                 'sequence' => '6',
                                 'text' => 'A complete surrender of inhibitions.',
                                 'headword' => 'abandon'
                               }
                        }
        };

(And that "noun" you see is the last (6th) definition/partofspeech element).

© Stack Overflow or respective owner

Related posts about Xml

Related posts about perl