How to access a parsing tree created using XML :: Parser?

I have a reference to an array that contains a number of references to arrays. Nested array references also contain array references. (This is a tree style XML :: Parser .)

my $Filename = "sample.xml";

my $Parser = new XML::Parser( Style => 'tree' );

my $Tree = $Parser->parsefile( $Filename );

Here $Treeis a reference to an array, it will be a reference to an array, the contents and nested depth depend on the xml file. I want to go through a nested array $Treeand print the contents.

+5
source share
2 answers

Here's a simplified version:

use strict;
use warnings;

sub printElement
{
  my ($tag, $content) = @_;

  if (ref $content) {
    # This is a XML element:
    my $attrHash = $content->[0];

    print "<$tag>";           # I'm ignoring attributes

    for (my $i = 1; $i < $#$content; $i += 2) {
      printElement(@$content[$i, $i+1]);
    }

    print "</$tag>";
  } else {
    # This is a text pseudo-element:
    print $content;             # I'm not encoding entities
  }
} # end printElement

sub printTree
{
  # The root tree is always a 2-element array
  # of the root element and its content:
  printElement(@{ shift @_ });
  print "\n";
}

# Example parse tree from XML::Parser:
my $tree =
    ['foo', [{}, 'head', [{id => "a"}, 0, "Hello ",  'em', [{}, 0, "there"]],
             'bar', [ {}, 0, "Howdy",  'ref', [{}]],
             0, "do"
            ]
    ];

printTree($tree);

, $attrHash. , , , XML. .: -)

+5
+1

All Articles