XML technologies / XML / Perl & XML / Tree-oriented processing / The tree mode of XML::Parser

(Excerpt from "Perl & XML" by Erik T. Ray & Jason McIntosh)

We used XML::Parser in Chapter 4 to generate event streams. Did you know that the same module can also build tree structures? Let us adapt our configuration file reader to read the file using XML::Parser and then print its tree. The modified program appears in the next example.

Example: building a tree with XML::Parser

# Initialisierung des Parsers und Lesen der Datei
use XML::Parser;
$parser = new XML::Parser( Style => 'Tree' );
my $tree = $parser->parsefile( shift @ARGV );

# Ausgabe der Baumstruktur
use Data::Dumper;
print Dumper( $tree );

Using the input file from this example produces the following output:

$tree = [           
     'konfiguration', [
       {}, 0, '\n',
       'zeichensatz', [
          { 'role' => 'console' }, 0, '\n',
          'groesse', [ {}, 0, '9' ], 0, '\n',
          'fname', [ {}, 0, 'Courier' ], 0, '\n'
       ], 0, '\n',
       'zeichensatz', [
          { 'role' => 'default' }, 0, '\n',
          'fname', [ {}, 0, 'Times New Roman' ], 0, '\n',
          'groesse', [ {}, 0, '14' ], 0, '\n'
        ], 0, '\n',        
        'zeichensatz', [
          { 'role' => 'titles' }, 0, '\n',
          'groesse', [ {}, 0, '10' ], 0, '\n',
          'fname', [ {}, 0, 'Helvetica' ], 0, '\n',
        ], 0, '\n',
       ]
     ];

This structure is more complex than that produced by XML::Simple. It preserves much more, including node types, node order and mixed text and child elements. Each node is represented by one or two list entries. Elements need two entries: the element name followed by its list of child nodes. Text nodes are represented by 0 followed by the text as a string. Element attributes are stored in a hash reference, the first entry in the element’s node list. Even whitespace between elements is preserved, represented as 0, \n. Child node order is preserved because the nodes are in a list. In some XML documents, such as books and animations, this order is important: the elements form an ordered sequence.

Unlike XML::Simple, XML::Parser cannot convert its own data structure back to XML. A bidirectional solution therefore needs something else, perhaps an object-oriented approach.

  

  

 

 

 

back to top