问题
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