且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl脚本来解析需要身份验证的Jenkins作业(config.xml)文件

更新时间:2023-12-04 08:59:28

我想出了一种使用经过身份验证的请求输出结果的方法.由于请求会输出xml内容以及标头响应,即:

I figured out a way to use the authenticated request to output results. Since the request outputs the xml content as well as the headers response, i.e:

HTTP/1.1 200 OK
Connection: close
Server: Jetty(8.y.z-SNAPSHOT)
Content-Type: application/xml
Client-Date: Wed, 30 Jul 2014 14:49:12 GMT
Client-Peer: 127.0.0.1:8080
Client-Response-Num: 1

<?xml version... 
<project>
  ....
  ....
</project>

我使用正则表达式提取 only 输出的xml部分并将其保存到文件中.从那里,我使用LibXML的 parse_file 方法来解析新编写的文件. (我有一个单独的子例程,该子例程使用 findnodes 方法提取要提取的特定节点.由于该解决方案处理了我遇到的身份验证问题,所以我没有发布它.)

I used a regular expression to extract only the xml part of the output and save it to file. From there I used LibXML's parse_file method to parse the newly written file. (I have a separate subroutine that uses the findnodes method to extract particular nodes I would like to extract. I didn't post it since this solution handles the authentication I was having trouble with).

解决方案:

use strict;
use warnings;
use XML::LibXML;
use Path::Class;
use LWP;
use HTTP::Cookies;

my $serverXmlUrl = "http\://localhost:8080/job/jobName/config.xml";
my $uagent = LWP::UserAgent->new(cookie_jar => HTTP::Cookies->new());
my $request = HTTP::Request->new( GET => $serverXmlUrl );
$request->authorization_basic( 'UserName', 'Password' );
my $result = $uagent->request($request);

if ( !$result->is_success ) {
    print "Failed\n";
} else {
    print "Success!\n";

    # Create new file to write to
    my $dir         = dir(".");
    my $file        = $dir->file("job.xml");
    my $file_handle = $file->openw();
    my $xml_content = $result->as_string; # full result output

    # Regex to store only xml content
    $xml_content =~ s/.*(<\?xml.*)/$1/s; 
    # Save xml_content to file
    $file_handle->print($xml_content);
    $file_handle->close();
    # Parse newly written file
    print "Parsing file... \n";
    my $parser = XML::LibXML->new();
    my $doc    = $parser->parse_file($file);
    print $doc;
}