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

一曲冷凌霜 提交于 2019-12-13 04:12:37

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/5744672/how-do-i-encode-key-value-pairs-using-perls-xmlsimple-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!