Home : General : Perl Programming :

General: Perl Programming: Re: [Watts] XML::Parser: Edit Log

Here is the list of edits for this post
Re: [Watts] XML::Parser
I prefer XML::Simple.

http://search.cpan.org/~grantm/XML-Simple-2.14/lib/XML/Simple.pm

Example (from my PingServices plugin):

Code:
<?xml version="1.0"?>
<methodCall>
<methodName>pingback.ping</methodName>
<params>
<param>
<value><string>http://www.mysite.com/blog/article.html</string></value>
</param>
<param>
<value><string>http://www.yoursite.com/blog/article.html</string></value>
</param>
</params>
</methodCall>

Converted to Perl data structure with:

Code:
sub pingback_req_parse
{
my $xml = $IN->post_data();
my $data = xml_to_hash($xml);

return (ref $data eq 'HASH')
? {
method => $data->{methodName},
from => $data->{params}->{param}->[0]->{value}->{string},
to => $data->{params}->{param}->[1]->{value}->{string}

}
: undef;
}

sub xml_to_hash
{
my $xml = shift;
$xml =~ s/^([^<]*)</</; #leading spaces before first tag breaks XML. remove them!

my $data = eval { XML::Simple::XMLin($xml) }; #eval to failsafe on bad input

return (ref $data eq 'HASH') ? $data : undef;
}

Note that there is an XML::RPC module I could have used for the above example, but XML::Simple is more portable as it lets me parse XML RPC calls as well as any other XML-like structure, such as Trackback RDF data from blogs, into a a more-or-less literal translation into a nested hash, where each XML tag or attribute is a hash key.

Philip
------------------
Limecat is not pleased.

Last edited by:

fuzzy logic: Sep 19, 2006, 10:33 AM

Edit Log: