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

Hi all. I'm currently in the process of learning how to use XPath and Perl to parse the following XML document (simplified):

<?xml version="1.0" encoding="UTF-8"?> <recordings type="array"> <recording type="Note"> <author-id type="integer">277210</author-id> <body>Text of the note goes here.</body> <id type="integer">34709871</id> </recording> <recording type="Comment"> <author-id type="integer">277210</author-id> <body>Text of a comment goes here</body> <id type="integer">34719228</id> </recording> </recordings>
I mainly need to know about <body> and <id>, thus using the following:
my $xml = XML::XPath->new (xml => $res->decoded_content); my $nodeset = $xml->find ("/recordings/recording"); foreach my $recording ($nodeset->get_nodelist) { my $id = $recording->find ("id")->string_value (); my $body = $recording->find ("body")->string_value (); # Do something with id and body here }
I would now also need to access the node attribute ("Note", "Comment") from within the foreach loop. Is there a method for extracting the attribute? Thanks, ~Oliver

Replies are listed 'Best First'.
Re: Accessing node attribute with XML::XPath
by kcott (Archbishop) on Nov 16, 2010 at 21:39 UTC

    I'd recommend looking at the test files for XML::XPath (these are the t/*.t files listed in the XML::XPath MANIFEST).

    This will cover what you need now, what you think you'll need soon and future needs you haven't anticipated.

    For more detailed information on XPath, see the W3C Recommendation.

    -- Ken

Re: Accessing node attribute with XML::XPath
by ikegami (Patriarch) on Nov 16, 2010 at 21:29 UTC

    Your query returns elements, and those have an getAttribute method.

    If you wanted to go the xpath route, the xpath to the attribute node would be attribute::type, for which @type is a shortcut.

      Perfect. I see that $recording->getAttribute('type') or $recording->findvalue('@type') work. Thanks a lot, ~Oliver
Re: Accessing node attribute with XML::XPath
by ikegami (Patriarch) on Nov 16, 2010 at 21:31 UTC

    Your query returns elements, and those have an getAttribute method.

    If you wanted to go the xpath route, the xpath to the attribute node would be attribute::type, for which @type is a shortcut.