How to order the input tags in Perl code using XML::Simple module for printing the output in XML format in specified order.. i have tried this
use XML::Si开发者_如何学Cmple;
use Data::Dumper;
open (FH,"> xml4.txt") || die ();
# create array
@arr = {
'name'=>['Cisco102'],
'SSIDConfig'=>[
{'SSID'=> [{'name'=>'Cisco102'}]}],
'connectionType'=>['ESS'],
'connectionMode'=>['auto'],
'autoSwitch'=>['false'],
'MSM'=>[{'security' =>[ { 'authEncryption' =>[{'authentication' => 'open',
'encryption' => 'WEP',
'useOneX' => 'false'
}],
'sharedKey' =>[ {
'keyType' => 'networkKey',
'protected' => 'false',
'keyMaterial' => '1234567890'
}]}]}]};
# create object
$xml = new XML::Simple(NoAttr=>1,RootName=>'WLAN Profile');
# convert Perl array ref into XML document
$data = $xml->XMLout(@arr,xmldecl => '<?xml version="1.0" encoding="US-ASCII"?>');
# access XML data
print FH $data;
but i am not getting the order which i required..i need the order ->name,SSID Config,Connectionmode,connectiontype,autoswitch,MSM .help me
It looks to me that you want 2 things for your XML:
- no attributes, hence the
NoAttr
option in the XML::Simple object creation - the order of the elements should be as specified
I am not sure why you don't want attributes in your XML, and why the data structure you use to create it has them. You may want to look into that. In any case XML::Simple gives you this feature.
For the second part, XML::Simple doesn't keep the order, and I have found no way to make it do it, so you will need something else.
For a quick and dirty solution, A little bit of XML::Twig in there would do:
# instead of the print FH $data; line
my $twig= XML::Twig->new( )->parse( $data);
$twig->root->set_content( map { $dtwig->root->first_child( $_) } (qw( name SSIDConfig connectionMode connectionType autoSwitch MSM)) );
$twig->print( \*FH);
A couple more comments:
- you can't use 'WLAN Profile` as the root tag, XML names cannot include spaces
- it is generally considered polite, when you ask a question about Perl, to show code that uses strict and warnings
- the proper way to open the output file would be
my $out_file= xml4.txt; open ( my $fh,'>', $out_file) or die "cannot create $out_file: $!";
(or useautodie
instead of thedie
), using 3 args open and lexical filehandles is a good habit (this message from the 3-arg open police department ;--)
Hashes aren't ordered. You could try using a Tie::IxHash (which looks like a hash, but maintains insertion order) instead of a normal hash. If that doesn't work, XML::Simple won't be of use to you.
精彩评论