programming-examples/perl/XML/The XML_Parser module provides a framework for parsing XML.pl

64 lines
1.7 KiB
Perl
Raw Normal View History

2019-11-15 12:59:38 +01:00
#With XML data, the main conditions include:
#The start of an XML tag
#The end of an XML tag
#The data between the start and end of an XML tag
#The start of the XML document
#The end of the XML document
#Parameters Passed to Your XML Callback Routines
#Routine Parameters
#Start XML::Parser object reference, element name, attribute, value.
#End XML::Parser object reference, element name
#Char XML::Parser object reference, text data
#Init XML::Parser object reference
#Final XML::Parser object reference
#!/usr/bin/perl -w
use XML::Parser;
$filename = 'yourXML.xml';
print "Opening $filename\n";
$parser = new XML::Parser(Handlers => {Start => \&tag_start,
End => \&tag_end,
Char => \&tag_char_data} );
$parser->parsefile($filename);
# Handles the start of a tag.
sub tag_start {
# Use shift to pull off elements.
my($obj) = shift;
my($elem) = shift;
my(%attrs) = @_;
print "<$elem ";
my(@keys) = keys( %attrs );
my($key);
foreach $key (@keys) {
print " $key=$attrs{$key} ";
}
print ">\n";
}
# Handles the end of a tag.
sub tag_end {
# Use shift to pull off elements.
my($obj) = shift;
my($elem) = shift;
print "</$elem>\n";
}
# Handles character data between the
# start and end of a tag.
sub tag_char_data {
# Use shift to pull off elements.
my($obj) = shift;
my($data) = shift;
# Note: no need for \n here in most documents.
print "$data";
}