2

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::Simple;
    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

4

2 回答 2

2

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 use autodie instead of the die), using 3 args open and lexical filehandles is a good habit (this message from the 3-arg open police department ;--)
于 2011-09-28T10:44:32.437 回答
2

哈希没有排序。您可以尝试使用Tie::IxHash(看起来像哈希,但保持插入顺序)而不是普通哈希。如果这不起作用,那么 XML::Simple 对您没有用处。

于 2011-09-28T06:26:28.630 回答