in reply to Re^2: Which XML module to use for this scenario?
in thread Which XML module to use for this scenario?

To get XML of a specific format, work backwards. Start with xml exactly how you like it and see what type of data structure it makes:

#!/usr/bin/perl use Data::Dumper; use XML::Simple; use strict; use warnings; my $data = do {local $/; <DATA>}; my $xml = XMLin($data); print Dumper($xml); __DATA__ <Parameters> <ParameterGroup ID="Group1"> <Parameter key="Key1">Some Value</Parameter> <Parameter key="Key2">Some Value</Parameter> <Parameter key="Key3">Some Value</Parameter> </ParameterGroup> <ParameterGroup ID="Group2"> <Parameter key="Key1">Some Value</Parameter> <Parameter key="Key2">Some Value</Parameter> <Parameter key="Key3">Some Value</Parameter> </ParameterGroup> </Parameters>

Doing this shows us our data structure. Now we just need to build it before translating to xml:

#!/usr/bin/perl use XML::Simple; use strict; use warnings; my $xml = { ParameterGroup => [ { ID => 'Group1', Parameter => { Key1 => {content => 'Some Value'}, Key2 => {content => 'Some Value'}, Key3 => {content => 'Some Value'}, }, }, { ID => 'Group1', Parameter => { Key1 => {content => 'Some Value'}, Key2 => {content => 'Some Value'}, Key3 => {content => 'Some Value'}, }, }, ]}; print XMLout($xml, RootName => 'Parameters', KeyAttr => 'key', );

Outputs

<Parameters> <ParameterGroup ID="Group1"> <Parameter key="Key1">Some Value</Parameter> <Parameter key="Key2">Some Value</Parameter> <Parameter key="Key3">Some Value</Parameter> </ParameterGroup> <ParameterGroup ID="Group1"> <Parameter key="Key1">Some Value</Parameter> <Parameter key="Key2">Some Value</Parameter> <Parameter key="Key3">Some Value</Parameter> </ParameterGroup> </Parameters>

Replies are listed 'Best First'.
Re^4: Which XML module to use for this scenario?
by Perllace (Acolyte) on Apr 23, 2011 at 13:27 UTC
    thanks wind.. this works.. but the user would have to specify the values of tags as an when he is scripting.. and therefore I cannot hard code the values inside the tag.. for this purpose..I have something like..
    $xml = { Parameter => [] }; push( @{ $xml->{Parameter} } , { key => $hash->{Key}, content => $hash->{Value} } );
    but this prints something like
    <Parameter key="ID1">Some Process a</Parameter> <Parameter key="ID2">Some Process b</Parameter> <Parameter key="ID3">Some Process c</Parameter>
    if I also want the ParameterGroup ID to be given by the user how can i do it..
      Then don't output the xml until the user has specified the complete data set, and translate it just like I showed.