KBEC-00019 - Using the Perl API without XML module experience

Article ID:360032832612
2 minute readKnowledge base

Summary

Functions in the ElectricCommander Perl API return XML objects. For customers who want to use Perl to interface with ElectricCommander, but who do not have experience with XML, it would be useful to be able to convert these XML objects to native Perl data types. This article shows how the XML::Simple module can be used to convert XML objects into Perl data structures.

This solution is useful for applications in which you deal with large amounts of data (multi-megabytes) in one response, where the performance burden of XPath might be very costly. Also, you can use this solution any place the power of XPath’s processing is not needed and the simplicity of dealing with native Perl variables is preferred.

Solution

  • Execute a call to a function in the ElectricCommander Perl API

  • Convert the result to an XML string

  • Use the XML::Simple XmlIn() function to convert it to a perl data structure

  • Use the Perl data structure to complete the desired task

Example

Here is an overview of the solution’s key elements, see the attached file for a full example that lists jobs and their completion outcome.

# Load the commander API
use ElectricCommander ();

# Load XPath to convert Commander object to an XML string
use XML::XPath;

# Create Commander connection
my $N = new ElectricCommander->new();

my $ec_jobs  = $N->getJobs();
my $xml_jobs = $ec_jobs->findnodes_as_string("/");

# Load Simple module and convert XML string XML string to perl hash reference
use XML::Simple qw(:strict);
my $pl_jobs = XMLin($xml_jobs,
                    forcearray => [],
                    keyattr => []
                   );

# Iterate over the list of jobs
my @jobs = @{$pl_jobs->{response}->{job}};
foreach my $s (@jobs) {
  print "$s->{jobId} ";
  print "$s->{start}  ";
  print "$s->{finish}  ";
  print "$s->{status}  ";
  print "$s->{outcome}  ";
  print "$s->{projectName}:$s->{procedureName}\n";
}