in reply to How to use XML::Parser
For what you want, the following would be a place to start:
(Updated code, adding an "End" handler, and an "if" condition in the "Char" handler, to make sure that "Char" strings from outside the tag(s) of interest do not get appended to the wrong hash values. It still won't do the right thing for more complicated markup structures, like:#!/usr/bin/perl use strict; use warnings; use XML::Parser; use Data::Dumper 'Dumper'; my $xml_data; { local $/; $xml_data = <DATA>; } my %my_hash; my $hash_key = ''; my $parser = XML::Parser->new( Handlers => { Start => sub { $hash_key = $_[1] }, Char => sub { $my_hash{$hash_key} .= $_[1] if ( $ha +sh_key ) }, End => sub { $hash_key = '' } }, ); $parser->parse( $xml_data ); print Dumper( \%my_hash ); __DATA__ <root> <tag1>My Tag1</tag1> <tag2>My Tag2</tag2> <tag3>My Tag3</tag3> </root>
But all you need in that case is to manage your "hash_key" tag names as a stack instead of a single value.)<root> some text <tag1>tag1 text</tag1> some more text <tag2>tag2 text <tag3>tag3 text</tag3> more tag2 text </tag2> and so on... </root>
|
|---|