Perl通过HTTP解析XML文件,并添加一些额外的行

时间:2014-09-24 01:27:32

标签: xml perl http

我正在尝试编写一个可以从远程服务器的XML文件中收集信息的脚本。远程服务器需要身份验证。我能够进行身份验证,因为它使用基本身份验证,但由于XML文件之前的所有行,我似乎无法解析数据。有没有办法避免获取所有这些行并正确解析XML文件?

代码

#! /usr/bin/perl

use LWP::UserAgent;
use HTTP::Request::Common;

use XML::Simple;

$ua = LWP::UserAgent->new;

$req = HTTP::Request->new(GET => 'https://192.168.1.10/getxml?/home/');
$ua->ssl_opts(SSL_verify_mode => SSL_VERIFY_NONE); #Used to ignore certificate
$req->authorization_basic('admin', 'test');
$test = $ua->request($req)->as_string;

print $test;
# create object
my $xml = new XML::Simple;

# read XML file
my $data = $xml->XMLin("$test");

# access XML data
print $data->{status}[0]{productID};

响应

HTTP/1.1 200 OK
Connection: close
Date: Wed, 24 Sep 2014 01:12:20 GMT
Server: 
Content-Length: 252
Content-Type: text/xml; charset=UTF-8
Client-Date: Wed, 24 Sep 2014 01:11:59 GMT
Client-Peer: 192.168.1.10:443
Client-Response-Num: 1
Client-SSL-Cert-Issuer: XXXXXXXXXXXX
Client-SSL-Cert-Subject: XXXXXXXXXXXXX
Client-SSL-Cipher: XXXXXXXXXXXX
Client-SSL-Socket-Class: IO::Socket::SSL

<?xml version="1.0"?>
<Status>
  <SystemUnit item="1">
    <ProductId item="1">TEST SYSTEM</ProductId>
  </SystemUnit>
</Status>
:1: parser error : Start tag expected, '<' not found
HTTP/1.1 200 OK

2 个答案:

答案 0 :(得分:4)

$test = $ua->request($req)->as_string;调用返回整个请求的字符串表示(标题加内容)。

将其更改为$test = $ua->request($req)->content;

这将仅返回内容,减去标题。

答案 1 :(得分:0)

我会找到第一个匹配的&lt;并从那里获得其余的数据。这将跳过您不感兴趣的第一项。代码看起来像:

$test =~ m/(<.*)/s;
my $xmlData = $1;
my $data = $xml->XMLin("$xmlData");
# Fix the print to get the item for which I believe you are trying to obtain
print $data->{SystemUnit}{ProductId}{content}."\n";

我们捕获&lt;以及使用s修饰符指示项目的所有内容应该被视为一个字符串(基本上忽略换行符)。 $ 1是来自匹配语句的捕获数据,我将其分配给变量,以防您要打印它或在调试器中查看它。另外,我添加了以下内容以获取“TEST SYSTEM”作为ProductId标记的内容。