0

I have a hash of the form

my $hash = {
    'Key' => "ID1",
    'Value' => "SomeProcess"
};

I need to convert this to an XML fragment of the form

<Parameter key="ID1">Some Process a</Parameter> 
<Parameter key="ID2">Some Process b</Parameter> 
<Parameter key="ID3">Some Process c</Parameter>

How can this be done?

Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
MarsMax
  • 91
  • 1
  • 8

1 Answers1

3

First of all, your sample is not a valid XML document, so XML::Simple takes a little jury-rigging in order to output it. It seems to expect to output documents, not so much fragments. But I was able to generate that output with this structure:

my $xml
    = {
        Parameter => [
          { key => 'ID1', content => 'Some Process a' }
        , { key => 'ID2', content => 'Some Process b' }
        , { key => 'ID3', content => 'Some Process c' }
        ]
    };


print XMLout( $xml, RootName => '' ); # <- omit the root

Just keep in mind that XML::Simple will not be able to read that back in.

Here's the output:

  <Parameter key="ID1">Some Process a</Parameter>
  <Parameter key="ID2">Some Process b</Parameter>
  <Parameter key="ID3">Some Process c</Parameter>

So if you can get your structure into the form I showed you, you would be able to print out your fragment with the RootName => '' parameter.

So, given your format, something like this might work:

$xml = { Parameter => [] };
push( @{ $xml->{Parameter} }
    , { key => $hash->{Key}, content => $hash->{Value} }
    );
Axeman
  • 29,660
  • 2
  • 47
  • 102
  • Thanks Axeman.. say I have something like Some Value Some Value Some Value Some Value Some Value Some Value In this case my understanding is that is the root node. am I right? how can i do it..? thanks again – MarsMax Apr 23 '11 at 06:42
  • @MarsMax: Yeah `XMLout( $xml, RootNode => 'Parameters' )` – Axeman Apr 23 '11 at 21:36