How to create response with attributes in XML nodes using Apache2 :: REST?

I am using Perl Apache2::REST , and the standard way to return data is to issue $resp->data() and assign a value. I have something like this

 my $text = { 'tag1' => 4, 'tag2' => 5, 'tag3' => 6, }; $resp->data()->{'text'} = {map { $_ => [$text ->{$_}] } keys %$text}; 

which gives me such an answer

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

I would like to know how to create a response with an attribute in XML node tag1 and create tags of the same type at the same level?

Required conclusion

 <response message="" status="200"> <data> <tag1 id="abcd"> 4 </tag1> <tag1> <tag3 id="xyz"> 6 </tag3> </tag1> </data> </response> 
+4
source share
3 answers

The solution to this is to use the perl XML::Simple module with ForceArray => 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; 
+1
source

I think it will work, but it will produce a slightly different way out.

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

Yours faithfully,

EDIT:

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

The module uses XML :: Simple without parameters, but RootName . Knowing that, we know that the following data structure will produce the desired result.

 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 a response element.)

+3
source

All Articles