简体   繁体   English

如何使用Apache2 :: REST在XML节点中创建具有属性的响应?

[英]How to create a response with attributes in XML nodes using Apache2::REST?

I am using the Perl Apache2::REST and the standard way of returning data is to issue $resp->data() and assign a value. 我使用的是Perl Apache2::REST ,返回数据的标准方法是发出$resp->data()并赋值。 I have something like this 我有类似的东西

my $text = {
    'tag1' => 4,
    'tag2' => 5,
    'tag3' => 6,
};

$resp->data()->{'text'} = {map { $_ => [$text ->{$_}] } keys %$text};

which gives me a response like this 这给了我这样的回应

<response message="" status="200">
  <data>
    <tag1>4</tag1>
    <tag2>5</tag2>
    <tag3>6</tag3>
  </data>
</response>

I would like to get to know how i create a response with an attribute in XML node tag1 and can create tags of the same type on the same level? 我想了解如何使用XML节点tag1的属性创建响应,并且可以在同一级别创建相同类型的标记?

Desired output is 期望的输出是

<response message="" status="200">
  <data>
    <tag1 id="abcd"> 4 </tag1>
    <tag1>
      <tag3 id="xyz"> 6 </tag3>
    </tag1>
  </data>
</response>

I think this will work, but it will produce a bit different output 我认为这会奏效,但会产生不同的输出

my $text2->{tag1} = [4,{tag3 => 6}];
$resp->data()->{'text'} = $text2;

regards, 问候,

EDIT: 编辑:

my $text2->{tag1} = [4,['val',{tag3 => 6}]]; 

The module uses XML::Simple with no options but RootName . 该模块使用XML :: Simple,但没有选项,只有RootName Knowing that, we know the following data structure will produce the output you want. 知道了,我们知道以下数据结构将产生您想要的输出。

my $data = {
   'tag1' => [
      {
         id => 'abcd',
         content => '4',
      },
      {
         'tag3' => [
            {
               id => 'xyz',
               content => '6',
            },
         ],
      },
   ],
};

Test: 测试:

use XML::Simple qw( XMLout );
print XMLout($data , RootName => 'data');

Output: 输出:

<data>
  <tag1 id="abcd">4</tag1>
  <tag1>
    <tag3 id="xyz">6</tag3>
  </tag1>
</data>

(It will provide the response element.) (它将提供response元素。)

The solution to this is to use the perl module XML::Simple with ForceArray => 1 解决方案是使用perl模块XML::SimpleForceArray => 1

$xml = '<tag1 a="' . '4' . '"b="4">';
$xml .= '<tag3 id="' . '3' . '">'; 
$xml .= '<tag2>' . '5' . '</tag2>';
$xml .= '</tag3>';
$xml .= '</tag1>';

my $tree = $simple->XMLin($xml, ForceArray => 1, KeyAttr => [ ]);
$resp->data()->{'xml'} = $tree;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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