home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _280959428ac645cc78859b4b220e07fa < prev    next >
Text File  |  2000-03-15  |  30KB  |  1,029 lines

  1. # XML::Parser
  2. #
  3. # Copyright (c) 1998 Larry Wall and Clark Cooper
  4. # All rights reserved.
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the same terms as Perl itself.
  8.  
  9. package XML::Parser;
  10.  
  11. use vars qw($VERSION %Built_In_Styles $have_LWP);
  12. use Carp;
  13.  
  14. BEGIN {
  15.   require XML::Parser::Expat;
  16.   $VERSION = '2.27';
  17.   die "Parser.pm and Expat.pm versions don't match"
  18.     unless $VERSION eq $XML::Parser::Expat::VERSION;
  19.   eval {
  20.     require 'LWP.pm';
  21.     require 'URI/URL.pm';
  22.   };
  23.   $have_LWP = not $@;
  24.   if ($have_LWP) {
  25.     import LWP;
  26.   }
  27. }
  28.  
  29. use strict;
  30.  
  31. sub new {
  32.   my ($class, %args) = @_;
  33.   my $style = $args{Style};
  34.   
  35.   my $nonexopt = $args{Non_Expat_Options} ||= {};
  36.   
  37.   $nonexopt->{Style}             = 1;
  38.   $nonexopt->{Non_Expat_Options} = 1;
  39.   $nonexopt->{Handlers}          = 1;
  40.   $nonexopt->{_HNDL_TYPES}       = 1;
  41.   
  42.   
  43.   $args{_HNDL_TYPES} = {%XML::Parser::Expat::Handler_Setters};
  44.   $args{_HNDL_TYPES}->{Init} = 1;
  45.   $args{_HNDL_TYPES}->{Final} = 1;
  46.   
  47.   $args{Handlers} ||= {};
  48.   my $handlers = $args{Handlers};
  49.   
  50.   if (defined($style)) {
  51.     my $stylepkg = $style;
  52.     
  53.     if ($stylepkg !~ /::/) {
  54.       $stylepkg = "\u$style";
  55.       
  56.       # I'm using the Built_In_Styles hash to define
  57.       # valid internal styles, since a style doesn't
  58.       # need to define any particular Handler to be valid.
  59.       # So I can't check for the existence of a particular sub.
  60.       
  61.       croak "Undefined style: $style"
  62.     unless defined($Built_In_Styles{$stylepkg});
  63.       $stylepkg = 'XML::Parser::' . $stylepkg;
  64.     }
  65.     
  66.     my $htype;
  67.     foreach $htype (keys %{$args{_HNDL_TYPES}}) {
  68.       # Handlers explicity given override
  69.       # handlers from the Style package
  70.       unless (defined($handlers->{$htype})) {
  71.     
  72.     # A handler in the style package must either have
  73.     # exactly the right case as the type name or a
  74.     # completely lower case version of it.
  75.     
  76.     my $hname = "${stylepkg}::$htype";
  77.     if (defined(&$hname)) {
  78.       $handlers->{$htype} = \&$hname;
  79.       next;
  80.     }
  81.     
  82.     $hname = "${stylepkg}::\L$htype";
  83.     if (defined(&$hname)) {
  84.       $handlers->{$htype} = \&$hname;
  85.       next;
  86.     }
  87.       }
  88.     }
  89.   }
  90.   
  91.   $handlers->{ExternEnt} ||= ($have_LWP
  92.                   ? \&lwp_ext_ent_handler
  93.                   : \&file_ext_ent_handler);
  94.  
  95.   $args{Pkg} ||= caller;
  96.   bless \%args, $class;
  97. }                # End of new
  98.  
  99. sub setHandlers {
  100.   my ($self, @handler_pairs) = @_;
  101.   
  102.   croak("Uneven number of arguments to setHandlers method")
  103.     if (int(@handler_pairs) & 1);
  104.   
  105.   my @ret;
  106.   while (@handler_pairs) {
  107.     my $type = shift @handler_pairs;
  108.     my $handler = shift @handler_pairs;
  109.     unless (defined($self->{_HNDL_TYPES}->{$type})) {
  110.       my @types = sort keys %{$self->{_HNDL_TYPES}};
  111.       
  112.       croak("Unknown Parser handler type: $type\n Valid types: @types");
  113.     }
  114.     push(@ret, $type, $self->{Handlers}->{$type});
  115.     $self->{Handlers}->{$type} = $handler;
  116.   }
  117.  
  118.   return @ret;
  119. }                # End of setHandlers
  120.  
  121. sub parse_start {
  122.   my $self = shift;
  123.   my @expat_options = ();
  124.  
  125.   my ($key, $val);
  126.   while (($key, $val) = each %{$self}) {
  127.     push (@expat_options, $key, $val)
  128.       unless exists $self->{Non_Expat_Options}->{$key};
  129.   }
  130.  
  131.   my %handlers = %{$self->{Handlers}};
  132.   my $init = delete $handlers{Init};
  133.   my $final = delete $handlers{Final};
  134.  
  135.   my $expatnb = new XML::Parser::ExpatNB(@expat_options, @_);
  136.   $expatnb->setHandlers(%handlers);
  137.  
  138.   &$init($expatnb)
  139.     if defined($init);
  140.  
  141.   $expatnb->{FinalHandler} = $final
  142.     if defined($final);
  143.  
  144.   return $expatnb;
  145. }
  146.  
  147. sub parse {
  148.   my $self = shift;
  149.   my $arg  = shift;
  150.   my @expat_options = ();
  151.   my ($key, $val);
  152.   while (($key, $val) = each %{$self}) {
  153.     push(@expat_options, $key, $val)
  154.       unless exists $self->{Non_Expat_Options}->{$key};
  155.   }
  156.   
  157.   my $expat = new XML::Parser::Expat(@expat_options, @_);
  158.   my %handlers = %{$self->{Handlers}};
  159.   my $init = delete $handlers{Init};
  160.   my $final = delete $handlers{Final};
  161.   
  162.   $expat->setHandlers(%handlers);
  163.   
  164.   &$init($expat)
  165.     if defined($init);
  166.   
  167.   my @result = ();
  168.   my $result = $expat->parse($arg);
  169.   
  170.   if ($result and defined($final)) {
  171.     if (wantarray) {
  172.       @result = &$final($expat);
  173.     }
  174.     else {
  175.       $result = &$final($expat);
  176.     }
  177.   }
  178.   
  179.   $expat->release;
  180.  
  181.   return unless defined wantarray;
  182.   return wantarray ? @result : $result;
  183. }                # End of parse
  184.  
  185. sub parsestring {
  186.   my $self = shift;
  187.   $self->parse(@_);
  188. }                # End of parsestring
  189.  
  190. sub parsefile {
  191.   my $self = shift;
  192.   my $file = shift;
  193.   local(*FILE);
  194.   open(FILE, $file) or  croak "Couldn't open $file:\n$!";
  195.   binmode(FILE);
  196.   my @ret;
  197.   my $ret;
  198.   
  199.   if (wantarray) {
  200.     eval {
  201.       @ret = $self->parse(*FILE, @_);
  202.     };
  203.   }
  204.   else {
  205.     eval {
  206.       $ret = $self->parse(*FILE, @_);
  207.     };
  208.   }
  209.   my $err = $@;
  210.   close(FILE);
  211.   die $err if $err;
  212.   
  213.   return unless defined wantarray;
  214.   return wantarray ? @ret : $ret;
  215. }                # End of parsefile
  216.  
  217. my %External_Entity_Table = ();
  218.  
  219. sub file_ext_ent_handler {
  220.   my ($exp, $base, $sys) = @_;    # We don't use pub id
  221.  
  222.   local(*ENT);
  223.  
  224.   my $name = $sys;
  225.  
  226.   # Prepend base only for relative URLs
  227.  
  228.   if (defined($base)
  229.       and not ($name =~ m!^(?:/|\w+:)!))
  230.     {
  231.       $name = $base . $sys;
  232.     }
  233.  
  234.   if ($name =~ s/^(\w+)://) {
  235.     my $method = $1;
  236.  
  237.     unless ($method eq 'file') {
  238.       $exp->{ErrorMessage}
  239.     .= "\nDefault external entity handler only deals with file URLs.";
  240.       return undef;
  241.     }
  242.   }
  243.  
  244.   if ($name =~ /^[|>+]/
  245.       or $name =~ /\|$/) {
  246.     $exp->{ErrorMessage}
  247.     .= "Perl IO controls not permitted in system id";
  248.     return undef;
  249.   }
  250.  
  251.   my $def = $External_Entity_Table{$name};
  252.   if (! defined($def)) {
  253.     unless (open(ENT, $name)) {
  254.       $exp->{ErrorMessage}
  255.     .= "Failed to open $name: $!";
  256.       return undef;
  257.     }
  258.     my $status;
  259.     $status = read(ENT, $def, -s $name);
  260.     close(ENT);
  261.  
  262.     unless (defined($status)) {
  263.       $exp->{ErrorMessage}
  264.     .= "Error reading $name: $!";
  265.       return undef;
  266.     }
  267.  
  268.     $External_Entity_Table{$name} = $def;
  269.   }
  270.  
  271.   return $def;
  272. }  # End file_ext_ent_handler
  273.  
  274. ##
  275. ## Note that this external entity handler reads the entire entity into
  276. ## memory, so it will choke on huge ones.
  277. ##
  278. sub lwp_ext_ent_handler {
  279.   my ($exp, $base, $sys) = @_;  # We don't use public id
  280.  
  281.   my $uri = new URI::URL($sys);
  282.   if (not $uri->scheme and $base) {
  283.     $uri = $uri->abs($base);
  284.   }
  285.   
  286.   my $scheme = $uri->scheme;
  287.   if (not $scheme or $scheme eq 'file') {
  288.     return file_ext_ent_handler($exp, $base, $sys);
  289.   }
  290.  
  291.   my $ua = ($exp->{_lwpagent} ||= new LWP::UserAgent());
  292.  
  293.   my $req = new HTTP::Request('GET', $uri);
  294.  
  295.   my $res = $ua->request($req);
  296.   if ($res->is_error) {
  297.     $exp->{ErrorMessage} .= "\n" . $res->status_line;
  298.     return undef;
  299.   }
  300.   
  301.   return $res->content;
  302. }  # End lwp_ext_ent_handler
  303.  
  304. ###################################################################
  305.  
  306. package XML::Parser::Debug;
  307. $XML::Parser::Built_In_Styles{Debug} = 1;
  308.  
  309. sub Start {
  310.   my $expat = shift;
  311.   my $tag = shift;
  312.   print STDERR "@{$expat->{Context}} \\\\ (@_)\n";
  313. }
  314.  
  315. sub End {
  316.   my $expat = shift;
  317.   my $tag = shift;
  318.   print STDERR "@{$expat->{Context}} //\n";
  319. }
  320.  
  321. sub Char {
  322.   my $expat = shift;
  323.   my $text = shift;
  324.   $text =~ s/([\x80-\xff])/sprintf "#x%X;", ord $1/eg;
  325.   $text =~ s/([\t\n])/sprintf "#%d;", ord $1/eg;
  326.   print STDERR "@{$expat->{Context}} || $text\n";
  327. }
  328.  
  329. sub Proc {
  330.   my $expat = shift;
  331.   my $target = shift;
  332.   my $text = shift;
  333.   print $expat,"\n";
  334.   print $expat->{Context}, "\n";
  335.   my @foo = @{$expat->{Context}};
  336.   print STDERR "@foo $target($text)\n";
  337. }
  338.  
  339. ###################################################################
  340.  
  341. package XML::Parser::Subs;
  342. $XML::Parser::Built_In_Styles{Subs} = 1;
  343.  
  344. sub Start {
  345.   no strict 'refs';
  346.   my $expat = shift;
  347.   my $tag = shift;
  348.   my $sub = $expat->{Pkg} . "::$tag";
  349.   eval { &$sub($expat, $tag, @_) };
  350. }
  351.  
  352. sub End {
  353.   no strict 'refs';
  354.   my $expat = shift;
  355.   my $tag = shift;
  356.   my $sub = $expat->{Pkg} . "::${tag}_";
  357.   eval { &$sub($expat, $tag) };
  358. }
  359.  
  360. ###################################################################
  361.  
  362. package XML::Parser::Tree;
  363. $XML::Parser::Built_In_Styles{Tree} = 1;
  364.  
  365. sub Init {
  366.   my $expat = shift;
  367.   $expat->{Lists} = [];
  368.   $expat->{Curlist} = $expat->{Tree} = [];
  369. }
  370.  
  371. sub Start {
  372.   my $expat = shift;
  373.   my $tag = shift;
  374.   my $newlist = [ { @_ } ];
  375.   push @{ $expat->{Lists} }, $expat->{Curlist};
  376.   push @{ $expat->{Curlist} }, $tag => $newlist;
  377.   $expat->{Curlist} = $newlist;
  378. }
  379.  
  380. sub End {
  381.   my $expat = shift;
  382.   my $tag = shift;
  383.   $expat->{Curlist} = pop @{ $expat->{Lists} };
  384. }
  385.  
  386. sub Char {
  387.   my $expat = shift;
  388.   my $text = shift;
  389.   my $clist = $expat->{Curlist};
  390.   my $pos = $#$clist;
  391.   
  392.   if ($pos > 0 and $clist->[$pos - 1] eq '0') {
  393.     $clist->[$pos] .= $text;
  394.   } else {
  395.     push @$clist, 0 => $text;
  396.   }
  397. }
  398.  
  399. sub Final {
  400.   my $expat = shift;
  401.   delete $expat->{Curlist};
  402.   delete $expat->{Lists};
  403.   $expat->{Tree};
  404. }
  405.  
  406. ###################################################################
  407.  
  408. package XML::Parser::Objects;
  409. $XML::Parser::Built_In_Styles{Objects} = 1;
  410.  
  411. sub Init {
  412.   my $expat = shift;
  413.   $expat->{Lists} = [];
  414.   $expat->{Curlist} = $expat->{Tree} = [];
  415. }
  416.  
  417. sub Start {
  418.   my $expat = shift;
  419.   my $tag = shift;
  420.   my $newlist = [ ];
  421.   my $class = "${$expat}{Pkg}::$tag";
  422.   my $newobj = bless { @_, Kids => $newlist }, $class;
  423.   push @{ $expat->{Lists} }, $expat->{Curlist};
  424.   push @{ $expat->{Curlist} }, $newobj;
  425.   $expat->{Curlist} = $newlist;
  426. }
  427.  
  428. sub End {
  429.   my $expat = shift;
  430.   my $tag = shift;
  431.   $expat->{Curlist} = pop @{ $expat->{Lists} };
  432. }
  433.  
  434. sub Char {
  435.   my $expat = shift;
  436.   my $text = shift;
  437.   my $class = "${$expat}{Pkg}::Characters";
  438.   my $clist = $expat->{Curlist};
  439.   my $pos = $#$clist;
  440.   
  441.   if ($pos >= 0 and ref($clist->[$pos]) eq $class) {
  442.     $clist->[$pos]->{Text} .= $text;
  443.   } else {
  444.     push @$clist, bless { Text => $text }, $class;
  445.   }
  446. }
  447.  
  448. sub Final {
  449.   my $expat = shift;
  450.   delete $expat->{Curlist};
  451.   delete $expat->{Lists};
  452.   $expat->{Tree};
  453. }
  454.  
  455. ################################################################
  456.  
  457. package XML::Parser::Stream;
  458. $XML::Parser::Built_In_Styles{Stream} = 1;
  459.  
  460. # This style invented by Tim Bray <tbray@textuality.com>
  461.  
  462. sub Init {
  463.   no strict 'refs';
  464.   my $expat = shift;
  465.   $expat->{Text} = '';
  466.   my $sub = $expat->{Pkg} ."::StartDocument";
  467.   &$sub($expat)
  468.     if defined(&$sub);
  469. }
  470.  
  471. sub Start {
  472.   no strict 'refs';
  473.   my $expat = shift;
  474.   my $type = shift;
  475.   
  476.   doText($expat);
  477.   $_ = "<$type";
  478.   
  479.   %_ = @_;
  480.   while (@_) {
  481.     $_ .= ' ' . shift() . '="' . shift() . '"';
  482.   }
  483.   $_ .= '>';
  484.   
  485.   my $sub = $expat->{Pkg} . "::StartTag";
  486.   if (defined(&$sub)) {
  487.     &$sub($expat, $type);
  488.   } else {
  489.     print;
  490.   }
  491. }
  492.  
  493. sub End {
  494.   no strict 'refs';
  495.   my $expat = shift;
  496.   my $type = shift;
  497.   
  498.   # Set right context for Text handler
  499.   push(@{$expat->{Context}}, $type);
  500.   doText($expat);
  501.   pop(@{$expat->{Context}});
  502.   
  503.   $_ = "</$type>";
  504.   
  505.   my $sub = $expat->{Pkg} . "::EndTag";
  506.   if (defined(&$sub)) {
  507.     &$sub($expat, $type);
  508.   } else {
  509.     print;
  510.   }
  511. }
  512.  
  513. sub Char {
  514.   my $expat = shift;
  515.   $expat->{Text} .= shift;
  516. }
  517.  
  518. sub Proc {
  519.   no strict 'refs';
  520.   my $expat = shift;
  521.   my $target = shift;
  522.   my $text = shift;
  523.   
  524.   $_ = "<?$target $text?>";
  525.   
  526.   my $sub = $expat->{Pkg} . "::PI";
  527.   if (defined(&$sub)) {
  528.     &$sub($expat, $target, $text);
  529.   } else {
  530.     print;
  531.   }
  532. }
  533.  
  534. sub Final {
  535.   no strict 'refs';
  536.   my $expat = shift;
  537.   my $sub = $expat->{Pkg} . "::EndDocument";
  538.   &$sub($expat)
  539.     if defined(&$sub);
  540. }
  541.  
  542. sub doText {
  543.   no strict 'refs';
  544.   my $expat = shift;
  545.   $_ = $expat->{Text};
  546.   
  547.   if (length($_)) {
  548.     my $sub = $expat->{Pkg} . "::Text";
  549.     if (defined(&$sub)) {
  550.       &$sub($expat);
  551.     } else {
  552.       print;
  553.     }
  554.     
  555.     $expat->{Text} = '';
  556.   }
  557. }
  558.  
  559. 1;
  560.  
  561. __END__
  562.  
  563. =head1 NAME
  564.  
  565. XML::Parser - A perl module for parsing XML documents
  566.  
  567. =head1 SYNOPSIS
  568.  
  569.   use XML::Parser;
  570.   
  571.   $p1 = new XML::Parser(Style => 'Debug');
  572.   $p1->parsefile('REC-xml-19980210.xml');
  573.   $p1->parse('<foo id="me">Hello World</foo>');
  574.  
  575.   # Alternative
  576.   $p2 = new XML::Parser(Handlers => {Start => \&handle_start,
  577.                      End   => \&handle_end,
  578.                      Char  => \&handle_char});
  579.   $p2->parse($socket);
  580.  
  581.   # Another alternative
  582.   $p3 = new XML::Parser(ErrorContext => 2);
  583.  
  584.   $p3->setHandlers(Char    => \&text,
  585.            Default => \&other);
  586.  
  587.   open(FOO, 'xmlgenerator |');
  588.   $p3->parse(*FOO, ProtocolEncoding => 'ISO-8859-1');
  589.   close(FOO);
  590.  
  591.   $p3->parsefile('junk.xml', ErrorContext => 3);
  592.  
  593. =begin man
  594. .ds PI PI
  595.  
  596. =end man
  597.  
  598. =head1 DESCRIPTION
  599.  
  600. This module provides ways to parse XML documents. It is built on top of
  601. L<XML::Parser::Expat>, which is a lower level interface to James Clark's
  602. expat library. Each call to one of the parsing methods creates a new
  603. instance of XML::Parser::Expat which is then used to parse the document.
  604. Expat options may be provided when the XML::Parser object is created.
  605. These options are then passed on to the Expat object on each parse call.
  606. They can also be given as extra arguments to the parse methods, in which
  607. case they override options given at XML::Parser creation time.
  608.  
  609. The behavior of the parser is controlled either by C<L</Style>> and/or
  610. C<L</Handlers>> options, or by L</setHandlers> method. These all provide
  611. mechanisms for XML::Parser to set the handlers needed by XML::Parser::Expat.
  612. If neither C<Style> nor C<Handlers> are specified, then parsing just
  613. checks the document for being well-formed.
  614.  
  615. When underlying handlers get called, they receive as their first parameter
  616. the I<Expat> object, not the Parser object.
  617.  
  618. =head1 METHODS
  619.  
  620. =over 4
  621.  
  622. =item new
  623.  
  624. This is a class method, the constructor for XML::Parser. Options are passed
  625. as keyword value pairs. Recognized options are:
  626.  
  627. =over 4
  628.  
  629. =item * Style
  630.  
  631. This option provides an easy way to create a given style of parser. The
  632. built in styles are: L<"Debug">, L<"Subs">, L<"Tree">, L<"Objects">,
  633. and L<"Stream">.
  634. Custom styles can be provided by giving a full package name containing
  635. at least one '::'. This package should then have subs defined for each
  636. handler it wishes to have installed. See L<"STYLES"> below
  637. for a discussion of each built in style.
  638.  
  639. =item * Handlers
  640.  
  641. When provided, this option should be an anonymous hash containing as
  642. keys the type of handler and as values a sub reference to handle that
  643. type of event. All the handlers get passed as their 1st parameter the
  644. instance of expat that is parsing the document. Further details on
  645. handlers can be found in L<"HANDLERS">. Any handler set here
  646. overrides the corresponding handler set with the Style option.
  647.  
  648. =item * Pkg
  649.  
  650. Some styles will refer to subs defined in this package. If not provided,
  651. it defaults to the package which called the constructor.
  652.  
  653. =item * ErrorContext
  654.  
  655. This is an Expat option. When this option is defined, errors are reported
  656. in context. The value should be the number of lines to show on either side
  657. of the line in which the error occurred.
  658.  
  659. =item * ProtocolEncoding
  660.  
  661. This is an Expat option. This sets the protocol encoding name. It defaults
  662. to none. The built-in encodings are: C<UTF-8>, C<ISO-8859-1>, C<UTF-16>, and
  663. C<US-ASCII>. Other encodings may be used if they have encoding maps in one
  664. of the directories in the @Encoding_Path list. Check L<"ENCODINGS"> for
  665. more information on encoding maps. Setting the protocol encoding overrides
  666. any encoding in the XML declaration.
  667.  
  668. =item * Namespaces
  669.  
  670. This is an Expat option. If this is set to a true value, then namespace
  671. processing is done during the parse. See L<XML::Parser::Expat/"Namespaces">
  672. for further discussion of namespace processing.
  673.  
  674. =item * NoExpand
  675.  
  676. This is an Expat option. Normally, the parser will try to expand references
  677. to entities defined in the internal subset. If this option is set to a true
  678. value, and a default handler is also set, then the default handler will be
  679. called when an entity reference is seen in text. This has no effect if a
  680. default handler has not been registered, and it has no effect on the expansion
  681. of entity references inside attribute values.
  682.  
  683. =item * Stream_Delimiter
  684.  
  685. This is an Expat option. It takes a string value. When this string is found
  686. alone on a line while parsing from a stream, then the parse is ended as if it
  687. saw an end of file. The intended use is with a stream of xml documents in a
  688. MIME multipart format. The string should not contain a trailing newline.
  689.  
  690. =item * ParseParamEnt
  691.  
  692. This is an Expat option. Unless standalone is set to "yes" in the XML
  693. declaration, setting this to a true value allows the external DTD to be read,
  694. and parameter entities to be parsed and expanded.
  695.  
  696. =item * Non-Expat-Options
  697.  
  698. If provided, this should be an anonymous hash whose keys are options that
  699. shouldn't be passed to Expat. This should only be of concern to those
  700. subclassing XML::Parser.
  701.  
  702. =back
  703.  
  704. =item  setHandlers(TYPE, HANDLER [, TYPE, HANDLER [...]])
  705.  
  706. This method registers handlers for various parser events. It overrides any
  707. previous handlers registered through the Style or Handler options or through
  708. earlier calls to setHandlers. By providing a false or undefined value as
  709. the handler, the existing handler can be unset.
  710.  
  711. This method returns a list of type, handler pairs corresponding to the
  712. input. The handlers returned are the ones that were in effect prior to
  713. the call.
  714.  
  715. See a description of the handler types in L<"HANDLERS">.
  716.  
  717. =item parse(SOURCE [, OPT => OPT_VALUE [...]])
  718.  
  719. The SOURCE parameter should either be a string containing the whole XML
  720. document, or it should be an open IO::Handle. Constructor options to
  721. XML::Parser::Expat given as keyword-value pairs may follow the SOURCE
  722. parameter. These override, for this call, any options or attributes passed
  723. through from the XML::Parser instance.
  724.  
  725. A die call is thrown if a parse error occurs. Otherwise it will return 1
  726. or whatever is returned from the B<Final> handler, if one is installed.
  727. In other words, what parse may return depends on the style.
  728.  
  729. =item parsestring
  730.  
  731. This is just an alias for parse for backwards compatibility.
  732.  
  733. =item parsefile(FILE [, OPT => OPT_VALUE [...]])
  734.  
  735. Open FILE for reading, then call parse with the open handle. The file
  736. is closed no matter how parse returns. Returns what parse returns.
  737.  
  738. =item parse_start([ OPT => OPT_VALUE [...]])
  739.  
  740. Create and return a new instance of XML::Parser::ExpatNB. Constructor
  741. options may be provided. If an init handler has been provided, it is
  742. called before returning the ExpatNB object. Documents are parsed by
  743. making incremental calls to the parse_more method of this object, which
  744. takes a string. A single call to the parse_done method of this object,
  745. which takes no arguments, indicates that the document is finished.
  746.  
  747. If there is a final handler installed, it is executed by the parse_done
  748. method before returning and the parse_done method returns whatever is
  749. returned by the final handler.
  750.  
  751. =back
  752.  
  753. =head1 HANDLERS
  754.  
  755. Expat is an event based parser. As the parser recognizes parts of the
  756. document (say the start or end tag for an XML element), then any handlers
  757. registered for that type of an event are called with suitable parameters.
  758. All handlers receive an instance of XML::Parser::Expat as their first
  759. argument. See L<XML::Parser::Expat/"METHODS"> for a discussion of the
  760. methods that can be called on this object.
  761.  
  762. =head2 Init        (Expat)
  763.  
  764. This is called just before the parsing of the document starts.
  765.  
  766. =head2 Final        (Expat)
  767.  
  768. This is called just after parsing has finished, but only if no errors
  769. occurred during the parse. Parse returns what this returns.
  770.  
  771. =head2 Start        (Expat, Element [, Attr, Val [,...]])
  772.  
  773. This event is generated when an XML start tag is recognized. Element is the
  774. name of the XML element type that is opened with the start tag. The Attr &
  775. Val pairs are generated for each attribute in the start tag.
  776.  
  777. =head2 End        (Expat, Element)
  778.  
  779. This event is generated when an XML end tag is recognized. Note that
  780. an XML empty tag (<foo/>) generates both a start and an end event.
  781.  
  782. =head2 Char        (Expat, String)
  783.  
  784. This event is generated when non-markup is recognized. The non-markup
  785. sequence of characters is in String. A single non-markup sequence of
  786. characters may generate multiple calls to this handler. Whatever the
  787. encoding of the string in the original document, this is given to the
  788. handler in UTF-8.
  789.  
  790. =head2 Proc        (Expat, Target, Data)
  791.  
  792. This event is generated when a processing instruction is recognized.
  793.  
  794. =head2 Comment        (Expat, Data)
  795.  
  796. This event is generated when a comment is recognized.
  797.  
  798. =head2 CdataStart    (Expat)
  799.  
  800. This is called at the start of a CDATA section.
  801.  
  802. =head2 CdataEnd        (Expat)
  803.  
  804. This is called at the end of a CDATA section.
  805.  
  806. =head2 Default        (Expat, String)
  807.  
  808. This is called for any characters that don't have a registered handler.
  809. This includes both characters that are part of markup for which no
  810. events are generated (markup declarations) and characters that
  811. could generate events, but for which no handler has been registered.
  812.  
  813. Whatever the encoding in the original document, the string is returned to
  814. the handler in UTF-8.
  815.  
  816. =head2 Unparsed        (Expat, Entity, Base, Sysid, Pubid, Notation)
  817.  
  818. This is called for a declaration of an unparsed entity. Entity is the name
  819. of the entity. Base is the base to be used for resolving a relative URI.
  820. Sysid is the system id. Pubid is the public id. Notation is the notation
  821. name. Base and Pubid may be undefined.
  822.  
  823. =head2 Notation        (Expat, Notation, Base, Sysid, Pubid)
  824.  
  825. This is called for a declaration of notation. Notation is the notation name.
  826. Base is the base to be used for resolving a relative URI. Sysid is the system
  827. id. Pubid is the public id. Base, Sysid, and Pubid may all be undefined.
  828.  
  829. =head2 ExternEnt    (Expat, Base, Sysid, Pubid)
  830.  
  831. This is called when an external entity is referenced. Base is the base to be
  832. used for resolving a relative URI. Sysid is the system id. Pubid is the public
  833. id. Base, and Pubid may be undefined.
  834.  
  835. This handler should either return a string, which represents the contents of
  836. the external entity, or return an open filehandle that can be read to obtain
  837. the contents of the external entity, or return undef, which indicates the
  838. external entity couldn't be found and will generate a parse error.
  839.  
  840. If an open filehandle is returned, it must be returned as either a glob
  841. (*FOO) or as a reference to a glob (e.g. an instance of IO::Handle). The
  842. parser will close the filehandle after using it.
  843.  
  844. A default handler, XML::Parser::default_ext_ent_handler, is installed
  845. for this. It only handles the file URL method and it assumes "file:" if
  846. it isn't there. The expat base method can be used to set a basename for
  847. relative pathnames. If no basename is given, or if the basename is itself
  848. a relative name, then it is relative to the current working directory.
  849.  
  850. =head2 Entity        (Expat, Name, Val, Sysid, Pubid, Ndata)
  851.  
  852. This is called when an entity is declared. For internal entities, the Val
  853. parameter will contain the value and the remaining three parameters will be
  854. undefined. For external entities, the Val parameter will be undefined, the
  855. Sysid parameter will have the system id, the Pubid parameter will have the
  856. public id if it was provided (it will be undefined otherwise), the Ndata
  857. parameter will contain the notation for unparsed entities. If this is a
  858. parameter entity declaration, then a '%' will be prefixed to the name.
  859.  
  860. Note that this handler and the Unparsed handler above overlap. If both are
  861. set, then this handler will not be called for unparsed entities.
  862.  
  863. =head2 Element        (Expat, Name, Model)
  864.  
  865. The element handler is called when an element declaration is found. Name
  866. is the element name, and Model is the content model as a string.
  867.  
  868. =head2 Attlist        (Expat, Elname, Attname, Type, Default, Fixed)
  869.  
  870. This handler is called for each attribute in an ATTLIST declaration.
  871. So an ATTLIST declaration that has multiple attributes will generate multiple
  872. calls to this handler. The Elname parameter is the name of the element with
  873. which the attribute is being associated. The Attname parameter is the name
  874. of the attribute. Type is the attribute type, given as a string. Default is
  875. the default value, which will either be "#REQUIRED", "#IMPLIED" or a quoted
  876. string (i.e. the returned string will begin and end with a quote character).
  877. If Fixed is true, then this is a fixed attribute.
  878.  
  879. =head2 Doctype        (Expat, Name, Sysid, Pubid, Internal)
  880.  
  881. This handler is called for DOCTYPE declarations. Name is the document type
  882. name. Sysid is the system id of the document type, if it was provided,
  883. otherwise it's undefined. Pubid is the public id of the document type,
  884. which will be undefined if no public id was given. Internal is the internal
  885. subset, given as a string. If there was no internal subset, it will be
  886. undefined. Internal will contain all whitespace, comments, processing
  887. instructions, and declarations seen in the internal subset. The declarations
  888. will be there whether or not they have been processed by another handler
  889. (except for unparsed entities processed by the Unparsed handler). However,
  890. comments and processing instructions will not appear if they've been processed
  891. by their respective handlers.
  892.  
  893. =head2 XMLDecl        (Expat, Version, Encoding, Standalone)
  894.  
  895. This handler is called for xml declarations. Version is a string containg
  896. the version. Encoding is either undefined or contains an encoding string.
  897. Standalone will be either true, false, or undefined if the standalone attribute
  898. is yes, no, or not made respectively.
  899.  
  900. =head1 STYLES
  901.  
  902. =head2 Debug
  903.  
  904. This just prints out the document in outline form. Nothing special is
  905. returned by parse.
  906.  
  907. =head2 Subs
  908.  
  909. Each time an element starts, a sub by that name in the package specified
  910. by the Pkg option is called with the same parameters that the Start
  911. handler gets called with.
  912.  
  913. Each time an element ends, a sub with that name appended with an underscore
  914. ("_"), is called with the same parameters that the End handler gets called
  915. with.
  916.  
  917. Nothing special is returned by parse.
  918.  
  919. =head2 Tree
  920.  
  921. Parse will return a parse tree for the document. Each node in the tree
  922. takes the form of a tag, content pair. Text nodes are represented with
  923. a pseudo-tag of "0" and the string that is their content. For elements,
  924. the content is an array reference. The first item in the array is a
  925. (possibly empty) hash reference containing attributes. The remainder of
  926. the array is a sequence of tag-content pairs representing the content
  927. of the element.
  928.  
  929. So for example the result of parsing:
  930.  
  931.   <foo><head id="a">Hello <em>there</em></head><bar>Howdy<ref/></bar>do</foo>
  932.  
  933. would be:
  934.              Tag   Content
  935.   ==================================================================
  936.   [foo, [{}, head, [{id => "a"}, 0, "Hello ",  em, [{}, 0, "there"]],
  937.           bar, [         {}, 0, "Howdy",  ref, [{}]],
  938.             0, "do"
  939.     ]
  940.   ]
  941.  
  942. The root document "foo", has 3 children: a "head" element, a "bar"
  943. element and the text "do". After the empty attribute hash, these are
  944. represented in it's contents by 3 tag-content pairs.
  945.  
  946. =head2 Objects
  947.  
  948. This is similar to the Tree style, except that a hash object is created for
  949. each element. The corresponding object will be in the class whose name
  950. is created by appending "::" and the element name to the package set with
  951. the Pkg option. Non-markup text will be in the ::Characters class. The
  952. contents of the corresponding object will be in an anonymous array that
  953. is the value of the Kids property for that object.
  954.  
  955. =head2 Stream
  956.  
  957. This style also uses the Pkg package. If none of the subs that this
  958. style looks for is there, then the effect of parsing with this style is
  959. to print a canonical copy of the document without comments or declarations.
  960. All the subs receive as their 1st parameter the Expat instance for the
  961. document they're parsing.
  962.  
  963. It looks for the following routines:
  964.  
  965. =over 4
  966.  
  967. =item * StartDocument
  968.  
  969. Called at the start of the parse .
  970.  
  971. =item * StartTag
  972.  
  973. Called for every start tag with a second parameter of the element type. The $_
  974. variable will contain a copy of the tag and the %_ variable will contain
  975. attribute values supplied for that element.
  976.  
  977. =item * EndTag
  978.  
  979. Called for every end tag with a second parameter of the element type. The $_
  980. variable will contain a copy of the end tag.
  981.  
  982. =item * Text
  983.  
  984. Called just before start or end tags with accumulated non-markup text in
  985. the $_ variable.
  986.  
  987. =item * PI
  988.  
  989. Called for processing instructions. The $_ variable will contain a copy of
  990. the PI and the target and data are sent as 2nd and 3rd parameters
  991. respectively.
  992.  
  993. =item * EndDocument
  994.  
  995. Called at conclusion of the parse.
  996.  
  997. =back
  998.  
  999. =head1 ENCODINGS
  1000.  
  1001. XML documents may be encoded in character sets other than Unicode as
  1002. long as they may be mapped into the Unicode character set. Expat has
  1003. further restrictions on encodings. Read the xmlparse.h header file in
  1004. the expat distribution to see details on these restrictions.
  1005.  
  1006. Expat has built-in encodings for: C<UTF-8>, C<ISO-8859-1>, C<UTF-16>, and
  1007. C<US-ASCII>. Encodings are set either through the XML declaration
  1008. encoding attribute or through the ProtocolEncoding option to XML::Parser
  1009. or XML::Parser::Expat.
  1010.  
  1011. For encodings other than the built-ins, expat calls the function
  1012. load_encoding in the Expat package with the encoding name. This function
  1013. looks for a file in the path list @XML::Parser::Expat::Encoding_Path, that
  1014. matches the lower-cased name with a '.enc' extension. The first one it
  1015. finds, it loads.
  1016.  
  1017. If you wish to build your own encoding maps, check out the XML::Encoding
  1018. module from CPAN.
  1019.  
  1020. =head1 AUTHORS
  1021.  
  1022. Larry Wall <F<larry@wall.org>> wrote version 1.0.
  1023.  
  1024. Clark Cooper <F<coopercc@netheaven.com>> picked up support, changed the API
  1025. for this version (2.x), provided documentation,
  1026. and added some standard package features.
  1027.  
  1028. =cut
  1029.