简体   繁体   中英

How to get a list of Jenkins Jobs using XML API

I got the raw xml data from Jenkins REST API http://jenkins-host:8080/api/xml . Now I am working on getting the job name list out of this xml into a perl array or variable. following is the format of xml API

<hudson>
<job>
  <name>Test_Job1</name>
  <url>http://jenkins-host:8080/job/Test_job1/</url>
  <color>red</color>
</job>
<job>
  <name>Test_job2</name>
  <url>http://jenkins-host:8080/job/Test_job2/</url>
  <color>red</color>
</job>
<view>
  <name>Test_View</name>
  <url>http://jenkins-host:8080/</url>
</view>
</hudson>

Here I want to store Only the job names into an array not the view name. Ex:

@list = (Test_job1, Test_job2)

With XML::Twig it would be:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my @jobs;
XML::Twig->new( twig_roots => { 'job/name' => sub { push @jobs, $_->text; } })
         ->parseurl( 'http://jenkins-host:8080/api/xml');
my $xml = <<XML;
<hudson>
<job>
  <name>Test_Job1</name>
  <url>http://jenkins-host:8080/job/Test_job1/</url>
  <color>red</color>
</job>
<job>
  <name>Test_job2</name>
  <url>http://jenkins-host:8080/job/Test_job2/</url>
  <color>red</color>
</job>
<view>
  <name>Test_View</name>
  <url>http://jenkins-host:8080/</url>
</view>
</hudson>
XML

my @rules = (
  'hudson' => sub { $_[1]->{name} },
  job  => sub { '@name' => $_[1]{name} },
  name => 'content',
  _default => undef,
);
my $xr = XML::Rules->new(rules => \@rules);
my $data = $xr->parse($xml);

print Dumper $data;

Or:

my @jobs;
my @rules = (
  job  => sub { push @jobs, $_[1]{name} },
  name => 'content',
  _default => undef,
);
my $xr = XML::Rules->new(rules => \@rules);
$xr->parse($xml);

print Dumper \@jobs;

The simplest thing to do is this regular expression.

my @matches = ( $xml =~ m(<name>(.*?)</name>)gs) ;

If the format of your XML is subject to frequent changes, then you'll want to consider an XML parser instead of this simple regex match.


Edit: adding an explanation

The regular expression assumes that you have all of the XML in one scalar variable, the 's' modifier tells Perl to treat entire string as one long line ('.' will match a newline), and the 'g' modifies tell Perl to search the entire string, rather than quitting on the first match.

The regex itself simply finds all name tag pairs, and captures what lives in between them. by adding the question mark to modify the '. ' pattern, we tell perl to be non-greedy, and so it stops capturing when it sees the first closing name tag. otherwise '. ' would match until the very last name closing tag and that is not what we want.

We could also have written the capture as ([^<]+). I suppose that's a matter of preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM