CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [Stefanik] Xml formatting: Edit Log



7stud
Enthusiast

Jan 13, 2013, 9:07 PM


Views: 1989
Re: [Stefanik] Xml formatting


Code
 
use strict;
use warnings;
use 5.012;

use XML::Parser;

my $xml = <<END_OF_XML;
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from color="red" age="25">Jani</from>
<from color="red" age="22">Jose</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
END_OF_XML


my $parser = new XML::Parser(

Handlers => {Start => \&start_of_tag,
End => \&end_of_tag,
Char => \&handle_text}
);

$parser->parse($xml);


my $found_target_tag = 0;

sub start_of_tag {
my($e, $element, %attrs) = @_;

if ($element eq 'from') {
if ($attrs{age} == 22) {
$found_target_tag = 1;
}
} elsif ($element eq 'body') {
$found_target_tag = 1;
}
}

sub handle_text {
if ($found_target_tag) {
my($e, $text) = @_;
say $text;
}
}

sub end_of_tag {
$found_target_tag = 0;
}

--output:--
Jose
Don't forget me this weekend!

However, there are much better XML modules that you can use. Check to see if you have any other XML modules installed:

$ perldoc perllocal


(This post was edited by 7stud on Jan 14, 2013, 1:42 AM)


Edit Log:
Post edited by 7stud (Enthusiast) on Jan 13, 2013, 9:15 PM
Post edited by 7stud (Enthusiast) on Jan 13, 2013, 9:23 PM
Post edited by 7stud (Enthusiast) on Jan 13, 2013, 9:24 PM
Post edited by 7stud (Enthusiast) on Jan 13, 2013, 9:32 PM
Post edited by 7stud (Enthusiast) on Jan 13, 2013, 9:33 PM
Post edited by 7stud (Enthusiast) on Jan 14, 2013, 1:41 AM
Post edited by 7stud (Enthusiast) on Jan 14, 2013, 1:42 AM
Post edited by 7stud (Enthusiast) on Jan 14, 2013, 1:42 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives