Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1028 lines
30 KiB

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