无法使用mojolicious将HTTP响应发送为xml

时间:2014-04-09 04:17:20

标签: perl mojolicious

在这里尝试学习Mojolicious。对于以下请求,当我尝试进入

时,我得到404
http://hostname:3000/xml

这是一个简单的脚本:

use Mojolicious::Lite;
use Data::Dumper;


get '/xml' => sub {
    my $self  = shift;
    $self->render(xml => "<employees>  
 <employee>  
      <id>1001</id>  
       <name>John Smith</name>  
 </employee>  
 <employee>  
      <id>1002</id>  
       <name>Jane Dole</name>  
 </employee>  
 </employees>"
    );
};

app->start;

这个脚本是从json的一个例子中采用的,它运行正常。不确定xml为什么不起作用。

1 个答案:

答案 0 :(得分:3)

只需指定format

即可
get '/xml' => sub {
    my $self  = shift;

    my $xml = <<'XML';
<employees>
<employee><id>1001</id><name>John Smith</name></employee>
<employee><id>1002</id><name>Jane Dole</name></employee>
</employees>
XML

    $self->render(data => $xml, format => 'xml');
};

响应标头等于以下内容:

Connection: keep-alive
Server: Mojolicious (Perl)
Content-Length: 140
Content-Type: application/xml
Date: Wed, 09 Apr 2014 05:36:05 GMT

200 OK

当然也可以将数据放在模板中:

get '/xml' => sub {
    my $self  = shift;

    $self->render('employees', format => 'xml');
};

app->start;

__DATA__

@@ employees.xml.ep
<employees>
<employee><id>1001</id><name>John Smith</name></employee>
<employee><id>1002</id><name>Jane Dole</name></employee>
</employees>