in reply to Parsing XML

Hi,

Look at this snippet:

foreach my $domain (@{$result->{CommandResponse}->{DomainGetListResult +}->{Domain}}) { print $domain->{Name} . "\n"; print $domain->{ID} . "\n"; print $domain->{Expires} . "\n"; }

Best regards
McA

Replies are listed 'Best First'.
Re^2: Parsing XML
by calebcall (Sexton) on Mar 08, 2014 at 06:43 UTC
    Perfect! Thanks. So simple now that I see what you did, it works great.

      You're welcome. But be aware, XML::Simple plays not nice sometimes. Change your xml file to the following and show what happens:

      <?xml version="1.0" encoding="utf-8"?> <ApiResponse Status="OK" xmlns="http://api.namecheap.com/xml.response" +> <Errors /> <Warnings /> <RequestedCommand>namecheap.domains.getList</RequestedCommand> <CommandResponse Type="namecheap.domains.getList"> <DomainGetListResult> <Domain ID="8888999" Name="Domain4.com" Expires="05/20/2015"/> </DomainGetListResult> <Paging> <TotalItems>4</TotalItems> <CurrentPage>1</CurrentPage> <PageSize>50</PageSize> </Paging> </CommandResponse> <Server>API02</Server> <GMTTimeDifference>--5:00</GMTTimeDifference> <ExecutionTime>0.008</ExecutionTime> </ApiResponse>

      You'll see your script dies.

      XML::Simple creates an array ref when it sees more than one element, but a simple hash ref when there is one.

      Instantiate you XML::Simple object this way to force that the one element is always handles as an array:

      my $result = $xml->XMLin("myouput.xml", ForceArray => ['Domain']);

      When you start learning XML handling modules have a look at XML::Twig.

      McA

Re^2: Parsing XML
by calebcall (Sexton) on Mar 11, 2014 at 01:53 UTC

    So this works great if there are multiple items (domains in this case) that return. I've got cases where only a singe domain will return and I get the following error:

    Not an ARRAY reference at ./namecheap.pl line 99

    Line 99 in the line my foreach loop begins on. In my uneducated opinion, it would be due to returning only a single result and referencing it using @. I've tried a few other stabs at being able to handle both a single and multiple results but can't come up with anything. My next guess is to try to find how long my results are (i.e. greater than one) and handle them separately...but that seems like a lot of redundant work having the exact same thing but for different results.

      Did you use ForceArray as McA suggested?

        I did.

        EDIT:

        Ooh, thanks, I just found the issue. I was using the ForceArray, but that was for the first API call. The second one needed a different element specified. Thanks again.

      That is problem with XML::Simple :) sure there are options but its easier to use XML::Rules , its is XML::Simple on steriods, exampe
        Thanks, guys. I'll give these other modules a look.