2014-09-24 37 views
3

我正在嘗試編寫一個腳本,該腳本可以從遠程服務器的XML文件中收集信息。遠程服務器需要認證。由於它使用基本身份驗證,因此我能夠進行身份驗證,但由於XML文件之前的所有行,似乎無法解析數據。有沒有辦法避免所有這些行並正確解析XML文件?Perl用一些額外的行通過HTTP解析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 

回答

4

$test = $ua->request($req)->as_string;調用返回整個請求(標頭加內容)的字符串表示形式。

將其更改爲$test = $ua->request($req)->content;

這將只返回內容,減去標題。

+0

而且,你猜對了,'$ test = $ ua-> request($ req) - > header'只會返回頭文件。參見[HTTP :: Request](https://metacpan.org/pod/release/GAAS/HTTP-Message-6.06/lib/HTTP/Request.pm) – dwarring 2014-09-24 04:12:18

0

我會找到的第<匹配,並從那裏獲取數據的其餘部分。這將跳過您不感興趣的第一項內容。該代碼是這樣:

$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"; 

我們捕捉隨後使用S修飾符來指示項目應被視爲字符的一個串<和一切(基本上忽略換行)。 $ 1是匹配語句中的捕獲數據,如果您想打印它或在調試器中查看它,我將它分配給一個變量。另外,我添加了以下內容以獲得「測試系統」作爲ProductId標籤的內容。

+0

謝謝!史努比的答案刪除了標題,你的答案是修復我的印刷聲明是完美的! – yusof 2014-09-24 11:15:08