For sure, getting your head around the concept of xml parsing can be tough at first, but I've found that the docs and API for
XML::Parser are the easiest to work with, in terms of starting with the basics and being able to do just about anything. I posted a snippet a while back that is rather dense but possibly instructive:
Get a structured tally of XML tags.
For what you want, the following would be a place to start:
#!/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>
(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:
<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>
But all you need in that case is to manage your "hash_key" tag names as a stack instead of a single value.)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.