开发者

How do I encode key-value pairs using Perl's XML::Simple module?

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"开发者_如何学Python>Some Process c</Parameter>

How can this be done?


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} }
    );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜