home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / perl5 / XML / PatAct / ToObjects.pm < prev   
Encoding:
Text File  |  2004-10-28  |  15.4 KB  |  586 lines

  1. #
  2. # Copyright (C) 1999 Ken MacLeod
  3. # XML::PatAct::ToObjects is free software; you can redistribute it and/or
  4. # modify it under the same terms as Perl itself.
  5. #
  6. # $Id: ToObjects.pm,v 1.5 1999/12/22 21:15:00 kmacleod Exp $
  7. #
  8.  
  9. # The original XML::Grove::ToObjects actually generated and compiled a
  10. # sub for matching actions, possibly a performance improvement of three
  11. # or four times over all the comparisons made in start_element() and
  12. # end_element().
  13.  
  14. use strict;
  15.  
  16. use UNIVERSAL;
  17.  
  18. package XML::PatAct::ToObjects;
  19. use vars qw{ $VERSION $name_re };
  20.  
  21. # will be substituted by make-rel script
  22. $VERSION = "0.08";
  23.  
  24. # FIXME I doubt this is a correct Perl RE for productions [4] and
  25. # [5] in the XML 1.0 specification, especially considering Unicode chars
  26. $name_re = '[A-Za-z_:][A-Za-z0-9._:-]*';
  27.  
  28. sub new {
  29.     my $type = shift;
  30.     my $self = ($#_ == 0) ? { %{ (shift) } } : { @_ };
  31.  
  32.     bless $self, $type;
  33.  
  34.     my $usage = <<'EOF';
  35. usage: XML::PatAct::ToObjects->new( Matcher => $matcher,
  36.                     Patterns => $patterns );
  37. EOF
  38.  
  39.     die "No Matcher specified\n$usage\n"
  40.     if !defined $self->{Matcher};
  41.     die "No Patterns specified\n$usage\n"
  42.     if !defined $self->{Patterns};
  43.  
  44.     # Parse action items
  45.     $self->{Actions} = [ ];
  46.     my $patterns = $self->{Patterns};
  47.     my $ii = 1;
  48.     while ($ii <= $#$patterns) {
  49.         if (ref $patterns->[$ii]) {
  50.         push @{$self->{Actions}},
  51.           $self->_parse_action($patterns->[$ii]);
  52.     } else {
  53.         # is a code fragment
  54.     }
  55.     $ii += 2;
  56.     }
  57.  
  58.     if (defined $self->{GroveBuilder}) {
  59.     require XML::Grove::Builder;
  60.     import XML::Grove::Builder;
  61.     $self->{GroveBuilder} = XML::Grove::Builder->new();
  62.     }
  63.  
  64.     return $self;
  65. }
  66.  
  67. sub start_document {
  68.     my ($self, $document) = @_;
  69.  
  70.     $self->{Matcher}->initialize($self);
  71.     $self->{Parents} = [ { Contents => [  ] } ];
  72.     $self->{ActionStack} = [ ];
  73.     $self->{States} = [ 'normal' ];
  74.     $self->{Document} = $document;
  75.     $self->{Names} = [ ];
  76.     $self->{Nodes} = [ ];
  77.     $self->{Data} = undef;
  78.     $self->{SourceIsGrove} = UNIVERSAL::isa($document, 'Data::Grove');
  79.     if (!defined $self->{CharacterDataType}) {
  80.     require Data::Grove;
  81.     import Data::Grove;
  82.     $self->{CharacterDataType} = 'Data::Grove::Characters';
  83.     }
  84. }
  85.  
  86. sub end_document {
  87.     my ($self, $document) = @_;
  88.  
  89.     $self->{Matcher}->finalize();
  90.     # FIXME check to make sure no other fields were assigned to
  91.     my $value = $self->{Parents}[0]{Contents};
  92.  
  93.     # release all the info that is just used during event handling
  94.     $self->{Matcher} = $self->{Parents} = $self->{ActionStack} = undef;
  95.     $self->{States} = $self->{Document} = $self->{Names} = undef;
  96.     $self->{Nodes} = $self->{Data} = $self->{SourceIsGrove} = undef;
  97.  
  98.     return $value;
  99. }
  100.  
  101. sub start_element {
  102.     my ($self, $element) = @_;
  103.  
  104.     push @{$self->{Names}}, $element->{Name};
  105.     push @{$self->{Nodes}}, $element;
  106.  
  107.     my $index = $self->{Matcher}->match($element,
  108.                     $self->{Names},
  109.                     $self->{Nodes});
  110.  
  111.     my $action;
  112.     if (!defined $index) {
  113.     $action = undef;
  114.     } else {
  115.     $action = $self->{Actions}[$index];
  116.     }
  117.  
  118.     push @{$self->{ActionStack}}, $action;
  119.  
  120.     my $state = $self->{States}[-1];
  121.     push @{$self->{States}}, $state;
  122.  
  123.     if (($state eq 'as-grove') and !$self->{SourceIsGrove}) {
  124.     $self->{GroveBuilder}->start_element($element);
  125.     }
  126.  
  127.     return if (($state ne 'normal') && ($state ne 'pcdata'));
  128.  
  129.     if (defined($action) and defined($action->{PCData})) {
  130.     $self->{States}[-1] = 'pcdata';
  131.     }
  132.  
  133.     if (!defined($action) or $action->{Holder}) {
  134.     # ignore this element but continue processing below
  135.     return;
  136.     }
  137.  
  138.     if ($action->{Ignore} or $action->{FieldValue}) {
  139.     # ignore (discard) this element and it's children
  140.     $self->{States}[-1] = 'discarding';
  141.     return;
  142.     }
  143.  
  144.     if ($action->{AsString}) {
  145.     $self->{Data} = [ ];
  146.     $self->{States}[-1] = 'as-string';
  147.     return;
  148.     }
  149.  
  150.     if ($action->{AsGrove}) {
  151.     $self->{States}[-1] = 'as-grove';
  152.     if (!$self->{SourceIsGrove}) {
  153.         $self->{GroveBuilder}->start_document( { } );
  154.         $self->{GroveBuilder}->start_element($element);
  155.     }
  156.     return;
  157.     }
  158.  
  159.     if (defined $action->{Make}) {
  160.     my @args;
  161.     if (defined $element->{Attributes}) {
  162.         if (defined $self->{CopyAttributes}) {
  163.         push @args, %{$element->{Attributes}};
  164.         } elsif ($self->{CopyId} && defined($element->{Attributes}{ID})) {
  165.         # FIXME use code from XML::Grove::IDs
  166.         push (@args, ID => $element->{Attributes}{ID});
  167.         }
  168.     }
  169.  
  170.     if (defined $action->{Args}) {
  171.         eval 'push (@args, (' . $action->{Args} . '))';
  172.         if ($@) {
  173.         warn "$@\nwhile processing pattern/action #$index\n";
  174.         }
  175.     }
  176.  
  177.     if ($action->{Make} eq 'HASH') {
  178.         push @{$self->{Parents}}, { @args };
  179.     } elsif ($action->{Make} eq 'ARRAY') {
  180.         push @{$self->{Parents}}, [ @args ];
  181.     } else {
  182.         my $is_defined = 0;
  183.         #eval "\$is_defined = defined %{$action->{Make}" . "::}";
  184.         if ($is_defined) {
  185.         push @{$self->{Parents}}, $action->{Make}->new( @args );
  186.         } else {
  187.         push (@{$self->{Parents}},
  188.               bless ({ @args }, $action->{Make}));
  189.         }
  190.     }
  191.  
  192.     if ($action->{ContentsAsGrove}) {
  193.         $self->{States}[-1] = 'as-grove';
  194.         if (!$self->{SourceIsGrove}) {
  195.         $self->{GroveBuilder}->start_document( { } );
  196.         }
  197.     }
  198.  
  199.     return;
  200.     }
  201.  
  202.     # Place to store all the rest of gathered contents
  203.     push (@{$self->{Parents}}, { } );
  204. }
  205.  
  206. sub end_element {
  207.     my ($self, $end_element) = @_;
  208.  
  209.     my $name = pop @{$self->{Names}};
  210.     my $element = pop @{$self->{Nodes}};
  211.  
  212.     my $action = pop @{$self->{ActionStack}};
  213.     my $state = pop @{$self->{States}};
  214.  
  215.     if ($state eq 'as-grove' and !$self->{SourceIsGrove}) {
  216.     $self->{GroveBuilder}->end_element($end_element);
  217.     }
  218.  
  219.     if (!defined($action) or $action->{Holder}) {
  220.     return;
  221.     }
  222.  
  223.     if ($action->{Ignore}) {
  224.     return;
  225.     }
  226.  
  227.     my $value;
  228.  
  229.     if ($action->{AsString}) {
  230.     $value = join("", @{$self->{Data}});
  231.     } elsif ($action->{AsGrove}) {
  232.     if ($self->{SourceIsGrove}) {
  233.         $value = $element;
  234.     } else {
  235.         # get just the root element of the document fragment
  236.         $value = $self->{GroveBuilder}->end_document({ })->{Contents}[0];
  237.     }
  238.     } elsif (defined $action->{FieldValue}) {
  239.     $value = $action->{FieldValue};
  240.     $value =~ s/%\{($name_re)\}/$element->{Attributes}{$1}/ge;
  241.     } elsif (defined $action->{Make}) {
  242.     $value = pop @{$self->{Parents}};
  243.     if ($action->{ContentsAsGrove}) {
  244.         if ($self->{SourceIsGrove}) {
  245.         $value->{Contents} = $element->{Contents};
  246.         } else {
  247.         $value->{Contents} =
  248.             $self->{GroveBuilder}->end_document({ })->{Contents};
  249.         }
  250.     }
  251.     } else {
  252.     $value = pop(@{$self->{Parents}})->{Contents};
  253.     }
  254.  
  255.     if ($action->{FieldIsArray}) {
  256.     push @{$self->{Parents}[-1]{$action->{Field}}}, $value;
  257.     } elsif (defined $action->{Field}) {
  258.     my $field = $action->{Field};
  259.     $field =~ s/%\{($name_re)\}/$element->{Attributes}{$1}/ge;
  260.     $self->{Parents}[-1]{$field} = $value;
  261.     } else {
  262.     my $ref = ref($self->{Parents}[-1]);
  263.     if ($ref eq 'ARRAY') {
  264.         push @{$self->{Parents}[-1]}, $value;
  265.     } else {
  266.         push @{$self->{Parents}[-1]{Contents}}, $value;
  267.     }
  268.     }
  269. }
  270.  
  271. sub characters {
  272.     my ($self, $characters) = @_;
  273.  
  274.     my $state = $self->{States}[-1];
  275.     if ($state eq 'as-string') {
  276.     push @{$self->{Data}}, $characters->{Data};
  277.     } elsif ($state eq 'as-grove' and !$self->{SourceIsGrove}) {
  278.     $self->{GroveBuilder}->characters($characters);
  279.     } elsif ($state eq 'pcdata') {
  280.     push (@{$self->{Parents}[-1]{Contents}},
  281.           $self->{CharacterDataType}->new(%$characters));
  282.     }
  283. }
  284.  
  285. # we ignore processing instructions and ignorable whitespace by not
  286. # defining those functions
  287.  
  288. ###
  289. ### private functions
  290. ###
  291.  
  292. sub _parse_action {
  293.     my $self = shift; my $source = shift;
  294.  
  295.     my $action = {};
  296.  
  297.     while ($#$source > -1) {
  298.     my $option = shift @$source;
  299.     if ($option eq '-holder') {
  300.         $action->{Holder} = 1;
  301.     } elsif ($option eq '-make') {
  302.         $action->{Make} = shift @$source;
  303.     } elsif ($option eq '-args') {
  304.         my $args = shift @$source;
  305.         $args =~ s/%\{($name_re)\}/\$element->{Attributes}{'$1'}/g;
  306.         $action->{Args} = $args;
  307.     } elsif ($option eq '-field') {
  308.         $action->{Field} = shift @$source;
  309.     } elsif ($option eq '-push-field') {
  310.         $action->{Field} = shift @$source;
  311.         $action->{FieldIsArray} = 1;
  312.     } elsif ($option eq '-as-string') {
  313.         $action->{AsString} = 1;
  314.     } elsif ($option eq '-value') {
  315.         $action->{FieldValue} = shift @$source;
  316.     } elsif ($option eq '-grove') {
  317.         $self->{GroveBuilder} = 1;
  318.         $action->{AsGrove} = 1;
  319.     } elsif ($option eq '-grove-contents') {
  320.         $self->{GroveBuilder} = 1;
  321.         $action->{ContentsAsGrove} = 1;
  322.     } elsif ($option eq '-ignore') {
  323.         $action->{Ignore} = 1;
  324.     } elsif ($option eq '-pcdata') {
  325.         $action->{PCData} = 1;
  326.     } else {
  327.         die "$option: undefined option\n";
  328.     }
  329.     }
  330.  
  331.     return $action;
  332. }
  333.  
  334. 1;
  335.  
  336. __END__
  337.  
  338. =head1 NAME
  339.  
  340. XML::PatAct::ToObjects - An action module for creating Perl objects
  341.  
  342. =head1 SYNOPSIS
  343.  
  344.  use XML::PatAct::ToObjects;
  345.  
  346.  my $patterns = [ PATTERN => [ OPTIONS ],
  347.           PATTERN => "PERL-CODE",
  348.           ... ];
  349.  
  350.  my $matcher = XML::PatAct::ToObjects->new( Patterns => $patterns,
  351.                         Matcher => $matcher,
  352.                         CopyId => 1,
  353.                         CopyAttributes => 1 );
  354.  
  355.  
  356. =head1 DESCRIPTION
  357.  
  358. XML::PatAct::ToObjects is a PerlSAX handler for applying
  359. pattern-action lists to XML parses or trees.  XML::PatAct::ToObjects
  360. creates Perl objects of the types and contents of the action items you
  361. define.
  362.  
  363. New XML::PatAct::ToObject instances are creating by calling `new()'.
  364. Parameters can be passed as a list of key, value pairs or a hash.
  365. `new()' requires the Patterns and Matcher parameters, the rest are
  366. optional:
  367.  
  368. =over 4
  369.  
  370. =item Patterns
  371.  
  372. The pattern-action list to apply.
  373.  
  374. =item Matcher
  375.  
  376. An instance of the pattern or query matching module.
  377.  
  378. =item CopyId
  379.  
  380. Causes the `ID' attribute, if any, in a source XML element to be
  381. copied to an `ID' attribute in newly created objects.  Note that IDs
  382. may be lost of no pattern matches that element or an object is not
  383. created (C<-make>) for that element.
  384.  
  385. =item CopyAttributes
  386.  
  387. Causes all attributes of the element to be copied to the newly created
  388. objects.
  389.  
  390. =back
  391.  
  392. Each action can either be a list of options defined below or a string
  393. containing a fragment of Perl code.  If the action is a string of Perl
  394. code then simple then some simple substitutions are made as described
  395. further below.
  396.  
  397. Options that can be used in an action item containing an option-list:
  398.  
  399. =over 4
  400.  
  401. =item B<-holder>
  402.  
  403. Ignore this element, but continue processing it's children (compare to
  404. B<-ignore>).  C<-pcdata> may be used with this option.
  405.  
  406. =item B<-ignore>
  407.  
  408. Ignore (discard) this element and it's children (compare to B<-holder>).
  409.  
  410. =item B<-pcdata>
  411.  
  412. Character data in this element should be copied to the C<Contents>
  413. field.
  414.  
  415. =item B<-make> I<PACKAGE>
  416.  
  417. Create an object blessed into I<PACKAGE>, and continue processing this
  418. element and it's children.  I<PACKAGE> may be the type `C<HASH>' to
  419. simply create an anonyous hash.
  420.  
  421. =item B<-args> I<ARGUMENTS>
  422.  
  423. Use I<ARGUMENTS> in creating the object specified by B<-make>.  This
  424. is commonly used to copy element attributes into fields in the newly
  425. created object.  For example:
  426.  
  427.   -make => 'HASH', -args => 'URL => %{href}'
  428.  
  429. would copy the `C<href>' attribute in an element to the `C<URL>' field
  430. of the newly created hash.
  431.  
  432. =item B<-field> I<FIELD>
  433.  
  434. Store this element, object, or children of this element in the parent
  435. object's field named by I<FIELD>.
  436.  
  437. =item B<-push-field> I<FIELD>
  438.  
  439. Similar to B<-field>, except that I<FIELD> is an array and the
  440. contents are pushed onto that array.
  441.  
  442. =item B<-value> I<VALUE>
  443.  
  444. Use I<VALUE> as a literal value to store in I<FIELD>, otherwise
  445. ignoring this element and it's children.  Only valid with B<-field> or
  446. B<-push-field>.  `C<%{I<ATTRIBUTE>}>' notation can be used to
  447. substitute the value of an attribute into the literal value.
  448.  
  449. =item B<-as-string>
  450.  
  451. Convert the contents of this element to a string (as in
  452. C<XML::Grove::AsString>) and store in I<FIELD>.  Only valid with
  453. B<-field> or B<-push-field>.
  454.  
  455. =item B<-grove>
  456.  
  457. Copy this element to I<FIELD> without further processing.  The element
  458. can then be processed later as the Perl objects are manipulated.  Only
  459. valid with B<-field> or B<-push-field>.  If ToObjects is used with
  460. PerlSAX, this will use XML::Grove::Builder to build the grove element.
  461.  
  462. =item B<-grove-contents>
  463.  
  464. Used with B<-make>, B<-grove-contents> creates an object but then
  465. takes all of the content of that element and stores it in Contents.
  466.  
  467. =back
  468.  
  469. If an action item is a string, that string is treated as a fragment of
  470. Perl code.  The following simple substitutions are performed on the
  471. fragment to provide easy access to the information being converted:
  472.  
  473. =over 4
  474.  
  475. =item B<@ELEM@>
  476.  
  477. The object that caused this action to be called.  If ToObjects is used
  478. with PerlSAX this will be a hash with the element name and attributes,
  479. with XML::Grove this will be the element object, with Data::Grove it
  480. will be the matching object, and with XML::DOM it will be an
  481. XML::DOM::Element.
  482.  
  483. =back
  484.  
  485. =head1 EXAMPLE
  486.  
  487. The example pattern-action list below will convert the following XML
  488. representing a Database schema:
  489.  
  490.     <schema>
  491.       <table>
  492.         <name>MyTable</name>
  493.         <summary>A short summary</summary>
  494.         <description>A long description that may
  495.           contain a subset of HTML</description>
  496.         <column>
  497.           <name>MyColumn1</name>
  498.           <summary>A short summary</summary>
  499.           <description>A long description</description>
  500.           <unique/>
  501.           <non-null/>
  502.           <default>42</default>
  503.         </column>
  504.       </table>
  505.     </schema>
  506.  
  507. into Perl objects looking like:
  508.  
  509.     [
  510.       { Name => "MyTable",
  511.         Summary => "A short summary",
  512.         Description => $grove_object,
  513.         Columns => [
  514.           { Name => "MyColumn1",
  515.             Summary => "A short summary",
  516.             Description => $grove_object,
  517.             Unique => 1,
  518.             NonNull => 1,
  519.             Default => 42
  520.           }
  521.         ]
  522.       }
  523.     ]
  524.  
  525. Here is a Perl script and pattern-action list that will perform the
  526. conversion using the simple name matching pattern module
  527. XML::PatAct::MatchName.  The script accepts a Schema XML file as an
  528. argument (C<$ARGV[0]>) to the script.  This script creates a grove as
  529. one of it's objects, so it requires the XML::Grove module.
  530.  
  531.     use XML::Parser::PerlSAX;
  532.     use XML::PatAct::MatchName;
  533.     use XML::PatAct::ToObjects;
  534.  
  535.     my $patterns = [
  536.       'schema'      => [ qw{ -holder                                  } ],
  537.       'table'       => [ qw{ -make Schema::Table                      } ],
  538.       'name'        => [ qw{ -field Name -as-string                   } ],
  539.       'summary'     => [ qw{ -field Summary -as-string                } ],
  540.       'description' => [ qw{ -field Description -grove                } ],
  541.       'column'      => [ qw{ -make Schema::Column -push-field Columns } ],
  542.       'unique'      => [ qw{ -field Unique -value 1                   } ],
  543.       'non-null'    => [ qw{ -field NonNull -value 1                  } ],
  544.       'default'     => [ qw{ -field Default -as-string                } ],
  545.     ];
  546.  
  547.     my $matcher = XML::PatAct::MatchName->new( Patterns => $patterns );
  548.     my $handler = XML::PatAct::ToObjects->new( Patterns => $patterns,
  549.                                                Matcher => $matcher);
  550.  
  551.     my $parser = XML::Parser::PerlSAX->new( Handler => $handler );
  552.     my $schema = $parser->parse(Source => { SystemId => $ARGV[0] } );
  553.  
  554. =head1 TODO
  555.  
  556. =over 4
  557.  
  558. =item *
  559.  
  560. It'd be nice if patterns could be applied even in B<-as-string> and
  561. B<-grove>.
  562.  
  563. =item *
  564.  
  565. Implement Perl code actions.
  566.  
  567. =item *
  568.  
  569. B<-as-xml> to write XML into the field.
  570.  
  571. =back
  572.  
  573.  
  574.  
  575. =head1 AUTHOR
  576.  
  577. Ken MacLeod, ken@bitsko.slc.ut.us
  578.  
  579. =head1 SEE ALSO
  580.  
  581. perl(1), Data::Grove(3)
  582.  
  583. ``Using PatAct Modules'' and ``Creating PatAct Modules'' in libxml-perl.
  584.  
  585. =cut
  586.