The XML::Parser module provides a framework for parsing XML. : SAX « XML « Perl






The XML::Parser module provides a framework for parsing XML.

   

#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";  
}  
    
  








Related examples in the same category

1.Check error in SAX parser
2.Check node name in SAX paser
3.Register handlers to SAX parser
4.SAX parser handler
5.Converting a comma separated list data source to XML
6.Stream XML::Parser
7.Using XML::Parser to parse xml file
8.Using XML:Simple to read and store the document
9.XML::Parasr style: Tree