Skip to content

Instantly share code, notes, and snippets.

@sids
Created July 24, 2008 10:30
Show Gist options
  • Save sids/2112 to your computer and use it in GitHub Desktop.
Save sids/2112 to your computer and use it in GitHub Desktop.
Perl: XML Parsing and creation examples.
http://gist.github.com/2112
XML parsing/creation examples in Perl.
#!/usr/bin/perl
use strict; use warnings;
use XML::Parser;
my $parser = new XML::Parser ( Handlers => { # Creates our parser object
Start => \&hdl_start,
End => \&hdl_end,
Char => \&hdl_char,
Default => \&hdl_def,
});
$parser->parse(\*DATA);
sub hdl_start {
my ($p, $elt, %attrs) = @_;
print "$elt starts with attributes\n";
print "\t\t$_ = $attrs{$_}\n" foreach (keys %attrs);
}
sub hdl_end {
my ($p, $elt) = @_;
print "$elt ends\n";
}
sub hdl_char {
my ($p, $str) = @_;
print "CHARACTER DATA: $str\n";
}
sub hdl_def {
}
__DATA__
<CHATTER><INFO site="http://perlmonks.org" sitename="Perl Monks">
Rendered by the Chatterbox XML Ticker</INFO>
<message author="OeufMayo" time="20010228112952">
test</message>
<message author="deprecated" time="20010228113142">
pong</message>
<message author="OeufMayo" time="20010228113153">
/me test again; :)</message>
<message author="OeufMayo" time="20010228113255">
<a href="#">please note the use of HTML
tags</a></message>
</CHATTER>
#!/usr/bin/perl
use strict; use warnings;
use XML::Twig;
my $t= XML::Twig->new( twig_handlers =>
{
'level(2)' => \&filter_doc
},
pretty_print => 'indented',
output_filter => 'safe'
);
$t->parsefile($ARGV[0]);
sub filter_doc {
my $t = shift;
my $e = shift;
my $docId = $e->first_child_text('docId');
if (defined $doc_ids{$docId}) {
$e->delete;
} else {
$doc_ids{$docId} = 1;
$e->flush;
}
}
#!/usr/bin/perl
use strict; use warnings;
use XML::Writer;
my $writer = new XML::Writer(DATA_INDENT => 2);
$writer->startTag("greeting",
"class" => "simple");
$writer->characters("Hello, world!");
$writer->endTag("greeting");
$writer->end();
#!/usr/bin/perl
use strict; use warnings;
use XML::Writer::Simple tags => [qw/p b i tt/];
print p("Hey, ",b("you"),"! ", i("Yes ", b("you")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment