2013-01-22 5 views
-1

Je veux analyser un document XML simple en hachage.Analyse XML en hachage avec XML :: Parser en Perl

<?xml version ="1.0"?> 
<catalog> 
    <book id = "bk101"> 
     <author>Bob</author> 
     <title>Batman</title> 
    </book> 
    <book id = "bk102"> 
     <author>Jerry</author> 
     <title>Superman</title> 
    </book> 
</catalog> 

La sortie attendue est quelque chose comme ceci.

$VAR1 = { 
    'catalog'=>{ 
      'bk101'=>[ 
        'author'=>'Bob', 
        'title'=>'Batman' 
        ] 
      'bk102'=>[ 
        'author'=>'Jerry', 
        'title'=>'Superman' 
        ] 
     } 
    } 

Je l'ai fait avec l'aide de XML::Simple et d'autres bibliothèques, mais je dois le faire avec XML::Parser, sans l'utilisation de la récursivité.

Comment est-ce que je ferais ceci en Perl?

+2

La première étape est de lire la documentation à https://metacpan.org/module/XML: : Analyseur et suivez-le. Ensuite, montrez-nous votre code, et dites-nous exactement ce que vous avez des problèmes ou ce que vous ne comprenez pas. – Perleone

+0

Pourquoi les restrictions? – runrig

Répondre

2

XML::Hash::LX::xml2hash() est proche de ce que vous cherchez:

#!/usr/bin/env perl 
use strict; 
use warnings qw(all); 

use Data::Dumper; 
use XML::Hash::LX; 

my $hash = xml2hash q(<?xml version ="1.0"?> 
    <catalog> 
     <book id = "bk101"> 
      <author>Bob</author> 
      <title>Batman</title> 
     </book> 
     <book id = "bk102"> 
      <author>Jerry</author> 
      <title>Superman</title> 
     </book> 
    </catalog> 
); 
print Dumper $hash; 

Prints:

$VAR1 = { 
      'catalog' => { 
         'book' => [ 
           { 
            'title' => 'Batman', 
            'author' => 'Bob', 
            '-id' => 'bk101' 
           }, 
           { 
            'title' => 'Superman', 
            'author' => 'Jerry', 
            '-id' => 'bk102' 
           } 
           ] 
        } 
     };