XML-Twig

 view release on metacpan or  search on metacpan

lib/XML/Twig.pm  view on Meta::CPAN

$PI        = '#PI';
$COMMENT   = '#COMMENT';
$ENT       = '#ENT';
$NOTATION  = '#NOTATION';

# element classes
$ELT     = '#ELT';
$TEXT    = '#TEXT';

# element properties
$ASIS    = '#ASIS';
$EMPTY   = '#EMPTY';

# used in parseurl to set the buffer size to the same size as in XML::Parser::Expat
$BUFSIZE = 32768;

# gi => index
%XML::Twig::gi2index=( '', 0, $PCDATA => 1, $CDATA => 2, $PI => 3, $COMMENT => 4, $ENT => 5);
# list of gi's
@XML::Twig::index2gi=( '', $PCDATA, $CDATA, $PI, $COMMENT, $ENT);

# gi's under this value are special
$XML::Twig::SPECIAL_GI= @XML::Twig::index2gi;

%XML::Twig::base_ent= ( '>' => '&gt;', '<' => '&lt;', '&' => '&amp;', "'" => '&apos;', '"' => '&quot;',);
foreach my $c ( "\n", "\r", "\t") { $XML::Twig::base_ent{$c}= sprintf( "&#x%02x;", ord( $c)); }

# now set some aliases
*find_nodes           = *get_xpath;               # same as XML::XPath
*findnodes            = *get_xpath;               # same as XML::LibXML
*getElementsByTagName = *descendants;
*descendants_or_self  = *descendants;             # valid in XML::Twig, not in XML::Twig::Elt
*find_by_tag_name     = *descendants;
*getElementById       = *elt_id;
*getEltById           = *elt_id;
*toString             = *sprint;
*create_accessors     = *att_accessors;

}

@ISA = qw(XML::Parser);

# fake gi's used in twig_handlers and start_tag_handlers
my $ALL    = '_all_';     # the associated function is always called
my $DEFAULT= '_default_'; # the function is called if no other handler has been

# some defaults
my $COMMENTS_DEFAULT= 'keep';
my $PI_DEFAULT      = 'keep';

# handlers used in regular mode
my %twig_handlers=( Start      => \&_twig_start,
                    End        => \&_twig_end,
                    Char       => \&_twig_char,
                    Entity     => \&_twig_entity,
                    Notation   => \&_twig_notation,
                    XMLDecl    => \&_twig_xmldecl,
                    Doctype    => \&_twig_doctype,
                    Element    => \&_twig_element,
                    Attlist    => \&_twig_attlist,
                    CdataStart => \&_twig_cdatastart,
                    CdataEnd   => \&_twig_cdataend,
                    Proc       => \&_twig_pi,
                    Comment    => \&_twig_comment,
                    Default    => \&_twig_default,
                    ExternEnt  => \&_twig_extern_ent,
      );

# handlers used when twig_roots is used and we are outside of the roots
my %twig_handlers_roots=
  ( Start      => \&_twig_start_check_roots,
    End        => \&_twig_end_check_roots,
    Doctype    => \&_twig_doctype,
    Char       => undef, Entity     => undef, XMLDecl    => \&_twig_xmldecl,
    Element    => undef, Attlist    => undef, CdataStart => undef,
    CdataEnd   => undef, Proc       => undef, Comment    => undef,
    Proc       => \&_twig_pi_check_roots,
    Default    =>  sub {}, # hack needed for XML::Parser 2.27
    ExternEnt  => \&_twig_extern_ent,
  );

# handlers used when twig_roots and print_outside_roots are used and we are
# outside of the roots
my %twig_handlers_roots_print_2_30=
  ( Start      => \&_twig_start_check_roots,
    End        => \&_twig_end_check_roots,
    Char       => \&_twig_print,
    Entity     => \&_twig_print_entity,
    ExternEnt  => \&_twig_print_entity,
    DoctypeFin => \&_twig_doctype_fin_print,
    XMLDecl    => sub { _twig_xmldecl( @_); _twig_print( @_); },
    Doctype   =>  \&_twig_print_doctype, # because recognized_string is broken here
    # Element    => \&_twig_print, Attlist    => \&_twig_print,
    CdataStart => \&_twig_print, CdataEnd   => \&_twig_print,
    Proc       => \&_twig_pi_check_roots, Comment    => \&_twig_print,
    Default    => \&_twig_print_check_doctype,
    ExternEnt  => \&_twig_extern_ent,
  );

# handlers used when twig_roots, print_outside_roots and keep_encoding are used
# and we are outside of the roots
my %twig_handlers_roots_print_original_2_30=
  ( Start      => \&_twig_start_check_roots,
    End        => \&_twig_end_check_roots,
    Char       => \&_twig_print_original,
    # I have no idea why I should not be using this handler!
    Entity     => \&_twig_print_entity,
    ExternEnt  => \&_twig_print_entity,
    DoctypeFin => \&_twig_doctype_fin_print,
    XMLDecl    => sub { _twig_xmldecl( @_); _twig_print_original( @_) },
    Doctype    => \&_twig_print_original_doctype,  # because original_string is broken here
    Element    => \&_twig_print_original, Attlist   => \&_twig_print_original,
    CdataStart => \&_twig_print_original, CdataEnd  => \&_twig_print_original,
    Proc       => \&_twig_pi_check_roots, Comment   => \&_twig_print_original,
    Default    => \&_twig_print_original_check_doctype,
  );

# handlers used when twig_roots and print_outside_roots are used and we are
# outside of the roots
my %twig_handlers_roots_print_2_27=
  ( Start      => \&_twig_start_check_roots,
    End        => \&_twig_end_check_roots,

lib/XML/Twig.pm  view on Meta::CPAN

        foreach my $tag (@tags) { $self->{twig_keep_spaces_in}->{$tag}=1; }
        delete $args{KeepSpacesIn};
      }

    if( $args{DiscardAllSpaces})
      {
        croak "cannot use both discard_all_spaces and discard_spaces_in" if( $args{DiscardSpacesIn});
        $self->{twig_discard_all_spaces}=1;
        delete $args{DiscardAllSpaces};
      }

    if( $args{DiscardSpacesIn})
      { $self->{twig_keep_spaces}=1;
        $self->{twig_discard_spaces_in}={};
        my @tags= @{$args{DiscardSpacesIn}};
        foreach my $tag (@tags) { $self->{twig_discard_spaces_in}->{$tag}=1; }
        delete $args{DiscardSpacesIn};
      }
    # discard spaces by default
    $self->{twig_discard_spaces}= 1 unless(  $self->{twig_keep_spaces});

    $args{Comments}||= $COMMENTS_DEFAULT;
    if( $args{Comments} eq 'drop')       { $self->{twig_keep_comments}= 0;    }
    elsif( $args{Comments} eq 'keep')    { $self->{twig_keep_comments}= 1;    }
    elsif( $args{Comments} eq 'process') { $self->{twig_process_comments}= 1; }
    else { croak "wrong value for comments argument: '$args{Comments}' (should be 'drop', 'keep' or 'process')"; }
    delete $args{Comments};

    $args{Pi}||= $PI_DEFAULT;
    if( $args{Pi} eq 'drop')       { $self->{twig_keep_pi}= 0;    }
    elsif( $args{Pi} eq 'keep')    { $self->{twig_keep_pi}= 1;    }
    elsif( $args{Pi} eq 'process') { $self->{twig_process_pi}= 1; }
    else { croak "wrong value for pi argument: '$args{Pi}' (should be 'drop', 'keep' or 'process')"; }
    delete $args{Pi};

    if( $args{KeepEncoding})
      {
        # set it in XML::Twig::Elt so print functions know what to do
        $self->set_keep_encoding( 1);
        $self->{parse_start_tag}= $args{ParseStartTag} || \&_parse_start_tag;
        delete $args{ParseStartTag} if defined( $args{ParseStartTag}) ;
        delete $args{KeepEncoding};
      }
    else
      { $self->set_keep_encoding( 0);
        if( $args{ParseStartTag})
          { $self->{parse_start_tag}= $args{ParseStartTag}; }
        else
          { delete $self->{parse_start_tag}; }
        delete $args{ParseStartTag};
      }

    if( $args{OutputFilter})
      { $self->set_output_filter( $args{OutputFilter});
        delete $args{OutputFilter};
      }
    else
      { $self->set_output_filter( 0); }

    if( $args{RemoveCdata})
      { $self->set_remove_cdata( $args{RemoveCdata});
        delete $args{RemoveCdata};
      }
    else
      { $self->set_remove_cdata( 0); }

    if( $args{OutputTextFilter})
      { $self->set_output_text_filter( $args{OutputTextFilter});
        delete $args{OutputTextFilter};
      }
    else
      { $self->set_output_text_filter( 0); }

    if( $args{KeepAttsOrder})
      { $self->{keep_atts_order}= $args{KeepAttsOrder};
        if( _use( 'Tie::IxHash'))
          { $self->set_keep_atts_order(  $self->{keep_atts_order}); }
        else
          { croak "Tie::IxHash not available, option keep_atts_order not allowed"; }
      }
    else
      { $self->set_keep_atts_order( 0); }

    if( $args{PrettyPrint})    { $self->set_pretty_print( $args{PrettyPrint}); }
    if( $args{EscapeGt})       { $self->escape_gt( $args{EscapeGt});           }
    if( $args{EmptyTags})      { $self->set_empty_tag_style( $args{EmptyTags}) }

    if( exists $args{Id})      { $ID= $args{Id};                     delete $args{ID};             }
    if( $args{NoProlog})       { $self->{no_prolog}= 1;              delete $args{NoProlog};       }
    if( $args{DoNotOutputDTD}) { $self->{no_dtd_output}= 1;          delete $args{DoNotOutputDTD}; }
    if( $args{LoadDTD})        { $self->{twig_read_external_dtd}= 1; delete $args{LoadDTD};        }
    if( $args{CharHandler})    { $self->setCharHandler( $args{CharHandler}); delete $args{CharHandler}; }

    if( $args{InputFilter})    { $self->set_input_filter(  $args{InputFilter}); delete  $args{InputFilter}; }
    if( $args{NoExpand})       { $self->setHandlers( %twig_noexpand_handlers); $self->{twig_no_expand}=1; }
    if( my $output_encoding= $args{OutputEncoding}) { $self->set_output_encoding( $output_encoding); delete $args{OutputFilter}; }

    if( my $tdh= $args{TopDownHandlers}) { $self->{twig_tdh}=1; delete $args{TopDownHandlers}; }

    if( my $acc_a= $args{AttAccessors})   { $self->att_accessors( @$acc_a);  }
    if( my $acc_e= $args{EltAccessors})   { $self->elt_accessors( isa( $acc_e, 'ARRAY') ? @$acc_e : $acc_e);   }
    if( my $acc_f= $args{FieldAccessors}) { $self->field_accessors( isa( $acc_f, 'ARRAY') ? @$acc_f : $acc_f); }

    if( $args{UseTidy}) { $self->{use_tidy}= 1; }
    $self->{tidy_options}= $args{TidyOptions} || {};

    if( $args{OutputHtmlDoctype}) { $self->{html_doctype}= 1; }

    $self->set_quote( $args{Quote} || 'double');

    # set handlers
    if( $self->{twig_roots})
      { if( $self->{twig_default_print})
          { if( $self->{twig_keep_encoding})
              { $self->setHandlers( %twig_handlers_roots_print_original); }
            else
              { $self->setHandlers( %twig_handlers_roots_print);  }
          }
        else
          { $self->setHandlers( %twig_handlers_roots); }
      }
    else
      { $self->setHandlers( %twig_handlers); }

    # XML::Parser::Expat does not like these handler to be set. So in order to

lib/XML/Twig.pm  view on Meta::CPAN

      my $add_decl;

      while( ! _check_xml( $xml) && $max_tries--)
        {
          # a couple of fixes for weird HTML::TreeBuilder errors
          if( $@=~ m{^\s*xml (or text )?declaration not at start of (external )?entity}i)
            { $$xml=~ s{<\?xml.*?\?>}{}g;
              #warn " fixed xml declaration in the wrong place\n";
            }
          elsif( $@=~ m{undefined entity})
            { $$xml=~ s{&(amp;)?Amp;}{&amp;}g if $HTML::TreeBuilder::VERSION < 4.00;
              if( _use( 'HTML::Entities::Numbered')) { $$xml=name2hex_xml( $$xml); }
              $$xml=~ s{&(\w+);}{ my $ent= $1; if( $ent !~ m{^(amp|lt|gt|apos|quote)$}) { "&amp;$ent;" } }eg;
            }
          elsif( $@=~ m{&Amp; used in html})
            # if $Amp; is used instead of &amp; then HTML::TreeBuilder's as_xml is tripped (old version)
            { $$xml=~ s{&(amp;)?Amp;}{&amp;}g if $HTML::TreeBuilder::VERSION < 4.00;
            }
          elsif( $@=~ m{^\s*not well-formed \(invalid token\)})
            { if( $HTML::TreeBuilder::VERSION < 4.00)
                { $$xml=~ s{&(amp;)?Amp;}{&amp;}g;
                  $$xml=~  s{(<[^>]* )(\d+=)"}{$1a$2"}g; # <table 1> comes out as <table 1="1">, "fix the attribute
                }
              my $q= '<img "="&#34;" '; # extracted so vim doesn't get confused
              if( _use( 'HTML::Entities::Numbered')) { $$xml=name2hex_xml( $$xml); }
              if( $$xml=~ m{$q})
                { $$xml=~ s{$q}{<img }g; # happens with <img src="foo.png"" ...
                }
              else
                { my $encoding= _encoding_from_meta( $tree);
                  unless( keys %xml_parser_encoding) { %xml_parser_encoding= _xml_parser_encodings(); }

                  if( ! $add_decl)
                    { if( $xml_parser_encoding{$encoding})
                        { $add_decl=1; }
                      elsif( $encoding eq 'euc-jp' && $xml_parser_encoding{'x-euc-jp-jisx0221'})
                        { $encoding="x-euc-jp-jisx0221"; $add_decl=1;}
                      elsif( $encoding eq 'shift-jis' && $xml_parser_encoding{'x-sjis-jisx0221'})
                        { $encoding="x-sjis-jisx0221";   $add_decl=1;}

                      if( $add_decl)
                        { $$xml=~ s{^(<\?xml.*?\?>)?}{<?xml version="1.0" encoding="$encoding"?>}s;
                          #warn "  added decl (encoding $encoding)\n";
                        }
                      else
                        { $$xml=~ s{^(<\?xml.*?\?>)?}{}s;
                          #warn "  converting to utf8 from $encoding\n";
                          $$xml= _to_utf8( $encoding, $$xml);
                        }
                    }
                  else
                    { $$xml=~ s{^(<\?xml.*?\?>)?}{}s;
                      #warn "  converting to utf8 from $encoding\n";
                      $$xml= _to_utf8( $encoding, $$xml);
                    }
                }
            }
        }

      # some versions of HTML::TreeBuilder escape CDATA sections
      $$xml=~ s{(&lt;!\[CDATA\[.*?\]\]&gt;)}{_unescape_cdata( $1)}eg;
  }

  sub _xml_parser_encodings
    { my @encodings=( 'iso-8859-1'); # this one is included by default, there is no map for it in @INC
      foreach my $inc (@INC)
        { push @encodings, map { basename( $_, '.enc') } glob( File::Spec->catdir( $inc => XML => Parser => Encodings => '*.enc')); }
      return map { $_ => 1 } @encodings;
    }
}

sub _unescape_cdata
  { my( $cdata)= @_;
    $cdata=~s{&lt;}{<}g;
    $cdata=~s{&gt;}{>}g;
    $cdata=~s{&amp;}{&}g;
    return $cdata;
  }

sub _as_XML {

    # fork of HTML::Element::as_XML, which is a little too buggy and inconsistent between versions for my liking
    my ($elt) = @_;
    my $xml= '';
    my $empty_element_map = $elt->_empty_element_map;

    my ( $tag, $node, $start );    # per-iteration scratch
    $elt->traverse(
        sub {
            ( $node, $start ) = @_;
            if ( ref $node )
              { # it's an element
                $tag = $node->{'_tag'};
                if ($start)
                  { # on the way in
                    foreach my $att ( grep { ! m{^(_|/$)} } keys %$node )
                       { # fix attribute names instead of dying
                         my $new_att= $att;
                         if( $att=~ m{^\d}) { $new_att= "a$att"; }
                         $new_att=~ s{[^\w\d:_-]}{}g;
                         $new_att ||= 'a';
                         if( $new_att ne $att) { $node->{$new_att}= delete $node->{$att}; }
                       }

                    if ( $empty_element_map->{$tag} && (!@{ $node->{'_content'} || []}) )
                      { $xml.= $node->starttag_XML( undef, 1 ); }
                    else
                      { $xml.= $node->starttag_XML(undef); }
                  }
                else
                 { # on the way out
                   unless ( $empty_element_map->{$tag} and !@{ $node->{'_content'} || [] } )
                    { $xml.= $node->endtag_XML();
                    }     # otherwise it will have been an <... /> tag.
                  }
              }
            elsif( $node=~ /<!\[CDATA\[/)  # the content includes CDATA
              {  foreach my $chunk (split /(<!\[CDATA\[.*?\]\]>)/s, $node) # chunks are CDATA sections or normal text
                  { $xml.= $chunk =~ m{<!\[CDATA\[} ? $chunk : _xml_escape( $chunk); }
              }
            else   # it's just text
              { $xml .= _xml_escape($node); }
            1;            # keep traversing
        }
    );
  return $xml;
}

sub _xml_escape
  { my( $html)= @_;
    $html =~ s{&(?!                     # An ampersand that isn't followed by...
                  (  \#[0-9]+;       |  #   A hash mark, digits and semicolon, or
                    \#x[0-9a-fA-F]+; |  #   A hash mark, "x", hex digits and semicolon, or
                    [\w]+;              #   A valid unicode entity name and semicolon
                  )
                )
              }

lib/XML/Twig.pm  view on Meta::CPAN

          if( ref($handlers->{$path}) && isa( $handlers->{$path}, 'CODE'));
      }
    return $previous_roots;
  }

sub _check_illegal_twig_roots_handlers
  { my( $handlers)= @_;
    foreach my $tag_handlers (values %{$handlers->{xpath_handler}})
      { foreach my $handler_data (@$tag_handlers)
          { if( my $type= $handler_data->{test_on_text})
              { croak "string() condition not supported on twig_roots option"; }
          }
      }
    return;
  }

# just store the reference to the expat object in the twig
sub _twig_init
   { # warn " in _twig_init...\n"; # DEBUG handler

    my $p= shift;
    my $t=$p->{twig};

    if( $t->{twig_parsing} ) { croak "cannot reuse a twig that is already parsing"; }
    $t->{twig_parsing}=1;

    $t->{twig_parser}= $p;
    if( $weakrefs) { weaken( $t->{twig_parser}); }

    # in case they had been created by a previous parse
    delete $t->{twig_dtd};
    delete $t->{twig_doctype};
    delete $t->{twig_xmldecl};
    delete $t->{twig_root};

    # if needed set the output filehandle
    $t->_set_fh_to_twig_output_fh();
    return;
  }

# uses eval to catch the parser's death
sub safe_parse
  { my $t= shift;
    eval { $t->parse( @_); } ;
    return $@ ? $t->_reset_twig_after_error : $t;
  }

sub safe_parsefile
  { my $t= shift;
    eval { $t->parsefile( @_); } ;
    return $@ ? $t->_reset_twig_after_error : $t;
  }

# restore a twig in a proper state so it can be reused for a new parse
sub _reset_twig
  { my $t= shift;
    $t->{twig_parsing}= 0;
    delete $t->{twig_current};
    delete $t->{extra_data};
    delete $t->{twig_dtd};
    delete $t->{twig_in_pcdata};
    delete $t->{twig_in_cdata};
    delete $t->{twig_stored_space};
    delete $t->{twig_entity_list};
    $t->root->delete if( $t->root);
    delete $t->{twig_root};
    return $t;
  }

sub _reset_twig_after_error
  { my $t= shift;
    $t->_reset_twig;
    return undef;
  }

sub _add_or_discard_stored_spaces
  { my $t= shift;
    $t->{twig_right_after_root}=0; #XX

    my $current= $t->{twig_current} or return; # ugly hack, with ignore on, twig_current can disappear
    return unless length $t->{twig_stored_spaces};
    my $current_gi= $current->gi;

    if( ! $t->{twig_discard_all_spaces})
      { if( ! defined( $t->{twig_space_policy}->{$current_gi}))
          { $t->{twig_space_policy}->{$current_gi}= _space_policy( $t, $current_gi); }
        if(    $t->{twig_space_policy}->{$current_gi} || ($t->{twig_stored_spaces}!~ m{\n}) || $t->{twig_preserve_space})
          { _insert_pcdata( $t, $t->{twig_stored_spaces} ); }
      }

    $t->{twig_stored_spaces}='';

    return;
  }

# the default twig handlers, which build the tree
sub _twig_start
   { # warn " in _twig_start...\n"; # DEBUG handler

    #foreach my $s (@_) { next if ref $s; warn "$s: ", is_utf8( $s) ? "has flag" : "FLAG NOT SET"; } # YYY

    my ($p, $gi, @att)= @_;
    my $t=$p->{twig};

    # empty the stored pcdata (space stored in case they are really part of
    # a pcdata element) or stored it if the space policy dictates so
    # create a pcdata element with the spaces if need be
    _add_or_discard_stored_spaces( $t);
    my $parent= $t->{twig_current};

    # if we were parsing PCDATA then we exit the pcdata
    if( $t->{twig_in_pcdata})
      { $t->{twig_in_pcdata}= 0;
        $t->_trigger_text_handler();

        $parent->del_twig_current;
        $parent= $parent->_parent;
      }

    # if we choose to keep the encoding then we need to parse the tag
    if( my $func = $t->{parse_start_tag})
      { ($gi, @att)= &$func($p->original_string); }
    elsif( $t->{twig_entities_in_attribute})
      {
       ($gi,@att)= _parse_start_tag( $p->recognized_string);
         $t->{twig_entities_in_attribute}=0;
      }

    # if we are using an external DTD, we need to fill the default attributes
    if( $t->{twig_read_external_dtd}) { _fill_default_atts( $t, $gi, \@att); }

    # filter the input data if need be
    if( my $filter= $t->{twig_input_filter})
      { $gi= $filter->( $gi);
        foreach my $att (@att) { $att= $filter->($att); }
      }

    my $ns_decl;
    if( $t->{twig_map_xmlns})
      { $ns_decl= _replace_ns( $t, \$gi, \@att); }

    my $elt= $t->{twig_elt_class}->new( $gi);
    $elt->set_atts( @att);

    # now we can store the tag and atts
    my $context= { $ST_TAG => $gi, $ST_ELT => $elt, @att};
    $context->{$ST_NS}= $ns_decl if $ns_decl;
    if( $weakrefs) { weaken( $context->{$ST_ELT}); }
    push @{$t->{_twig_context_stack}}, $context;

    $parent->del_twig_current if( $parent);
    $t->{twig_current}= $elt;
    $elt->set_twig_current;

    if( $parent)
      { my $prev_sibling= $parent->_last_child;
        if( $prev_sibling)
          { $prev_sibling->set_next_sibling( $elt);
            $elt->set_prev_sibling( $prev_sibling);
          }

        $elt->set_parent( $parent);
        unless( $parent->_first_child) { $parent->set_first_child( $elt); }
        $parent->set_last_child( $elt);
      }
    else
      { # processing root
        $t->set_root( $elt);
        # call dtd handler if need be
        $t->{twig_dtd_handler}->($t, $t->{twig_dtd})
          if( defined $t->{twig_dtd_handler});

        # set this so we can catch external entities

lib/XML/Twig.pm  view on Meta::CPAN

# can be used to deal with xsi:type attributes
sub original_uri
  { my( $t, $prefix)= @_;
    my $ST_NS  = '##ns' ;
    foreach my $ns (map { $_->{$ST_NS} if  $_->{$ST_NS} } reverse @{$t->{_twig_context_stack}})
      { return $ns->{$prefix} || next; }
    return;
  }

sub _fill_default_atts
  { my( $t, $gi, $atts)= @_;
    my $dtd= $t->{twig_dtd};
    my $attlist= $dtd->{att}->{$gi};
    my %value= @$atts;
    foreach my $att (keys %$attlist)
      { if(   !exists( $value{$att})
            && exists( $attlist->{$att}->{default})
            && ( $attlist->{$att}->{default} ne '#IMPLIED')
          )
          { # the quotes are included in the default, so we need to remove them
            my $default_value= substr( $attlist->{$att}->{default}, 1, -1);
            push @$atts, $att, $default_value;
          }
      }
    return;
  }

# the default function to parse a start tag (in keep_encoding mode)
# can be overridden with the parse_start_tag method
# only works for 1-byte character sets
sub _parse_start_tag
  { my $string= shift;
    my( $gi, @atts);

    # get the gi (between < and the first space, / or > character)
    if( $string=~ s{^<\s*($REG_TAG_NAME)\s*[\s>/]}{}s)
      { $gi= $1; }
    else
      { croak "error parsing tag '$string'"; }
    while( $string=~ s{^([^\s=]*)\s*=\s*(["'])(.*?)\2\s*}{}s)
      { push @atts, $1, $3; }
    return $gi, @atts;
  }

sub set_root
  { my( $t, $elt)= @_;
    $t->{twig_root}= $elt;
    if( $elt)
      { $elt->{twig}= $t;
        if( $weakrefs) { weaken(  $elt->{twig}); }
      }
    return $t;
  }

sub _twig_end
   { # warn " in _twig_end...\n"; # DEBUG handler
    my ($p, $gi)  = @_;

    my $t=$p->{twig};

    if( $t->{twig_in_pcdata} )
      { $t->_trigger_text_handler(); }

    if( $t->{twig_map_xmlns}) { $gi= $t->_replace_prefix( $gi); }

    _add_or_discard_stored_spaces( $t);

    # the new twig_current is the parent
    my $elt= $t->{twig_current};
    $elt->del_twig_current;

    # if we were parsing PCDATA then we exit the pcdata too
    if( $t->{twig_in_pcdata})
      {
        $t->{twig_in_pcdata}= 0;
        $elt= $elt->_parent if($elt->_parent);
        $elt->del_twig_current;
      }

    # parent is the new current element
    my $parent= $elt->_parent;
    $t->{twig_current}= $parent;

    if( $parent)
      { $parent->set_twig_current;
        # twig_to_be_normalized
        if( $parent->{twig_to_be_normalized}) { $parent->normalize; $parent->{twig_to_be_normalized}=0; }
      }

    if( $t->{extra_data})
      { $elt->_set_extra_data_before_end_tag( $t->{extra_data});
        $t->{extra_data}='';
      }

    if( $t->{twig_handlers})
      { # look for handlers
        my @handlers= _handler( $t, $t->{twig_handlers}, $gi);

        if( $t->{twig_tdh})
          { if( @handlers) { push @{$t->{twig_handlers_to_trigger}}, [ $elt, \@handlers ]; }
            if( my $all= $t->{twig_handlers}->{handlers}->{$ALL})
              { push @{$t->{twig_handlers_to_trigger}}, [ $elt, [$all] ]; }
          }
        else
          {
            local $_= $elt; # so we can use $_ in the handlers

            foreach my $handler ( @handlers)
              { $handler->($t, $elt) || last; }
            # call _all_ handler if needed
            my $all= $t->{twig_handlers}->{handlers}->{$ALL};
            if( $all)
              { $all->($t, $elt); }
            if( @handlers || $all) { $t->{twig_right_after_root}=0; }
          }
      }

    # if twig_roots is set for the element then set appropriate handler
    if(  $t->{twig_root_depth} and ($p->depth == $t->{twig_root_depth}) )
      { if( $t->{twig_default_print})
          { # select the proper fh (and store the currently selected one)
            $t->_set_fh_to_twig_output_fh();
            if( !($p->depth==1)) { $t->{twig_right_after_root}=1; } #XX
            if( $t->{twig_keep_encoding})
              { $p->setHandlers( %twig_handlers_roots_print_original); }
            else
              { $p->setHandlers( %twig_handlers_roots_print); }
          }
        else
          { $p->setHandlers( %twig_handlers_roots); }
      }

    if( $elt->att( 'xml:space') && (  $elt->att( 'xml:space') eq 'preserve')) { $t->{twig_preserve_space}--; }

    pop @{$t->{_twig_context_stack}};

lib/XML/Twig.pm  view on Meta::CPAN

          }
      }
    return;
  }

# return the list of handler that can be activated for an element
# (either of CODE ref's or 1's for twig_roots)

sub _handler
  { my( $t, $handlers, $gi)= @_;

    my @found_handlers=();
    my $found_handler;

    foreach my $handler ( map { @$_ } grep { $_ } $handlers->{xpath_handler}->{$gi}, $handlers->{xpath_handler}->{'*'})
      {  my $trigger= $handler->{trigger};
         if( my $found_path= $trigger->( $t->{_twig_context_stack}))
          { my $found_handler= $handler->{handler};
            push @found_handlers, $found_handler;
          }
      }

    # if no handler found call default handler if defined
    if( !@found_handlers && defined $handlers->{handlers}->{$DEFAULT})
      { push @found_handlers, $handlers->{handlers}->{$DEFAULT}; }

    if( @found_handlers and $t->{twig_do_not_chain_handlers})
      { @found_handlers= ($found_handlers[0]); }

    return @found_handlers; # empty if no handler found

  }

sub _replace_prefix
  { my( $t, $name)= @_;
    my $p= $t->parser;
    my $uri= $p->namespace( $name);
    # try to get the namespace from default if none is found (for attributes)
    # this should probably be an option
    if( !$uri and( $name!~/^xml/)) { $uri= $p->expand_ns_prefix( '#default'); }
    if( $uri)
      { if (my $mapped_prefix= $t->{twig_map_xmlns}->{$uri} || $DEFAULT_URI2NS{$uri})
          { return "$mapped_prefix:$name"; }
        else
          { my $prefix= _a_proper_ns_prefix( $p, $uri);
            if( $prefix eq '#default') { $prefix=''; }
            return $prefix ? "$prefix:$name" : $name;
          }
      }
    else
      { return $name; }
  }

sub _twig_char
   { # warn " in _twig_char...\n"; # DEBUG handler

    my ($p, $string)= @_;
    my $t=$p->{twig};

    if( $t->{twig_keep_encoding})
      { if( !$t->{twig_in_cdata})
          { $string= $p->original_string(); }
        else
          {
            use bytes;
            if( length( $string) < 1024)
              { $string= $p->original_string(); }
            else
              { #warn "dodgy case";
                # TODO original_string does not hold the entire string, but $string is wrong
                # I believe due to a bug in XML::Parser
                # for now, we use the original string, even if it means that it's been converted to utf8
              }
          }
      }

    if( $t->{twig_input_filter}) { $string= $t->{twig_input_filter}->( $string); }
    if( $t->{twig_char_handler}) { $string= $t->{twig_char_handler}->( $string); }

    my $elt= $t->{twig_current};

    if(    $t->{twig_in_cdata})
      { # text is the continuation of a previously created cdata
        $elt->append_cdata( $t->{twig_stored_spaces} . $string);
      }
    elsif( $t->{twig_in_pcdata})
      { # text is the continuation of a previously created pcdata
        if( $t->{extra_data})
          { $elt->_push_extra_data_in_pcdata( $t->{extra_data}, length( $elt->{pcdata}));
            $t->{extra_data}='';
          }
        $elt->append_pcdata( $string);
      }
    else
      {
        # text is just space, which might be discarded later
        if( $string=~/\A\s*\Z/s)
          {
            if( $t->{extra_data})
              { # we got extra data (comment, pi), lets add the spaces to it
                $t->{extra_data} .= $string;
              }
            else
              { # no extra data, just store the spaces
                $t->{twig_stored_spaces}.= $string;
              }
          }
        else
          { my $new_elt= _insert_pcdata( $t, $t->{twig_stored_spaces}.$string);
            $elt->del_twig_current;
            $new_elt->set_twig_current;
            $t->{twig_current}= $new_elt;
            $t->{twig_in_pcdata}=1;
            if( $t->{extra_data})
              { $new_elt->_push_extra_data_in_pcdata( $t->{extra_data}, 0);
                $t->{extra_data}='';
              }
          }
      }
    return;
  }

sub _twig_cdatastart
   { # warn " in _twig_cdatastart...\n"; # DEBUG handler

    my $p= shift;
    my $t=$p->{twig};

    $t->{twig_in_cdata}=1;
    my $cdata=  $t->{twig_elt_class}->new( $CDATA);
    my $twig_current= $t->{twig_current};

    if( $t->{twig_in_pcdata})
      { # create the node as a sibling of the PCDATA
        $cdata->set_prev_sibling( $twig_current);
        $twig_current->set_next_sibling( $cdata);
        my $parent= $twig_current->_parent;
        $cdata->set_parent( $parent);
        $parent->set_last_child( $cdata);
        $t->{twig_in_pcdata}=0;
      }
    else
      { # we have to create a PCDATA element if we need to store spaces
        if( $t->_space_policy($twig_current->gi) && $t->{twig_stored_spaces})
          { _insert_pcdata( $t, $t->{twig_stored_spaces}); }
        $t->{twig_stored_spaces}='';

        # create the node as a child of the current element
        $cdata->set_parent( $twig_current);
        if( my $prev_sibling= $twig_current->_last_child)
          { $cdata->set_prev_sibling( $prev_sibling);
            $prev_sibling->set_next_sibling( $cdata);
          }
        else
          { $twig_current->set_first_child( $cdata); }
        $twig_current->set_last_child( $cdata);
      }

    $twig_current->del_twig_current;
    $t->{twig_current}= $cdata;
    $cdata->set_twig_current;
    if( $t->{extra_data}) { $cdata->set_extra_data( $t->{extra_data}); $t->{extra_data}='' };
    return;
  }

sub _twig_cdataend
   { # warn " in _twig_cdataend...\n"; # DEBUG handler

    my $p= shift;
    my $t=$p->{twig};

    $t->{twig_in_cdata}=0;

    my $elt= $t->{twig_current};
    $elt->del_twig_current;
    my $cdata= $elt->cdata;
    $elt->_set_cdata( $cdata);

    push @{$t->{_twig_context_stack}}, { $ST_TAG => $CDATA };

    if( $t->{twig_handlers})
      { # look for handlers
        my @handlers= _handler( $t, $t->{twig_handlers}, $CDATA);
        local $_= $elt; # so we can use $_ in the handlers
        foreach my $handler ( @handlers) { $handler->($t, $elt) || last; }
      }

    pop @{$t->{_twig_context_stack}};

    $elt= $elt->_parent;
    $t->{twig_current}= $elt;
    $elt->set_twig_current;

    $t->{twig_long_cdata}=0;
    return;
  }

sub _pi_elt_handlers
  { my( $t, $pi)= @_;
    my $pi_handlers= $t->{twig_handlers}->{pi_handlers} || return;
    foreach my $handler ( $pi_handlers->{$pi->target}, $pi_handlers->{''})
      { if( $handler) { local $_= $pi; $handler->( $t, $pi) || last; } }
  }

sub _pi_text_handler
  { my( $t, $target, $data)= @_;
    if( my $handler= $t->{twig_handlers}->{pi_handlers}->{$target})
      { return $handler->( $t, $target, $data); }
    if( my $handler= $t->{twig_handlers}->{pi_handlers}->{''})
      { return $handler->( $t, $target, $data); }
    return defined( $data) && $data ne ''  ? "<?$target $data?>" : "<?$target?>" ;
  }

sub _comment_elt_handler
  { my( $t, $comment)= @_;
    if( my $handler= $t->{twig_handlers}->{handlers}->{$COMMENT})
      { local $_= $comment; $handler->($t, $comment); }
  }

sub _comment_text_handler
  { my( $t, $comment)= @_;
    if( my $handler= $t->{twig_handlers}->{handlers}->{$COMMENT})
      { $comment= $handler->($t, $comment);
        if( !defined $comment || $comment eq '') { return ''; }
      }
    return "<!--$comment-->";
  }

sub _twig_comment
   { # warn " in _twig_comment...\n"; # DEBUG handler
    my( $p, $comment_text)= @_;
    my $t=$p->{twig};

    if( $t->{twig_keep_encoding}) { $comment_text= substr( $p->original_string(), 4, -3); }

    $t->_twig_pi_comment( $p, $COMMENT, $t->{twig_keep_comments}, $t->{twig_process_comments},
                          '_set_comment', '_comment_elt_handler', '_comment_text_handler', $comment_text
                        );
    return;
  }

sub _twig_pi
   { # warn " in _twig_pi...\n"; # DEBUG handler

    my( $p, $target, $data)= @_;
    my $t=$p->{twig};

    if( $t->{twig_keep_encoding})
      { my $pi_text= substr( $p->original_string(), 2, -2);
        ($target, $data)= split( /\s+/, $pi_text, 2);
      }

    $t->_twig_pi_comment( $p, $PI, $t->{twig_keep_pi}, $t->{twig_process_pi},
                          '_set_pi', '_pi_elt_handlers', '_pi_text_handler', $target, $data
                        );
    return;
  }

sub _twig_pi_comment
  { my( $t, $p, $type, $keep, $process, $set, $elt_handler, $text_handler, @parser_args)= @_;

    if( $t->{twig_input_filter})
          { foreach my $arg (@parser_args) { $arg= $t->{twig_input_filter}->( $arg); } }

    # if pi/comments are to be kept then we piggyback them to the current element
    if( $keep)
      { # first add spaces
        if( $t->{twig_stored_spaces})
              { $t->{extra_data}.= $t->{twig_stored_spaces};
                $t->{twig_stored_spaces}= '';
              }

        my $extra_data= $t->$text_handler( @parser_args);
        $t->{extra_data}.= $extra_data;

      }
    elsif( $process)
      {
        my $twig_current= $t->{twig_current}; # defined unless we are outside of the root

        my $elt= $t->{twig_elt_class}->new( $type);
        $elt->$set( @parser_args);
        if( $t->{extra_data})
          { $elt->set_extra_data( $t->{extra_data});
            $t->{extra_data}='';
          }

        if( ! $t->root)
          { $t->_add_cpi_outside_of_root( leading_cpi => $elt);
          }
        elsif( $t->{twig_in_pcdata})
          { $t->_trigger_text_handler();
            # create the node as a sibling of the PCDATA
            $elt->paste_after( $twig_current);
            $t->{twig_in_pcdata}=0;
          }
        elsif( $twig_current)
          { # we have to create a PCDATA element if we need to store spaces
            if( $t->_space_policy($twig_current->gi) && $t->{twig_stored_spaces})
              { _insert_pcdata( $t, $t->{twig_stored_spaces}); }
            $t->{twig_stored_spaces}='';
            # create the node as a child of the current element
            $elt->paste_last_child( $twig_current);
          }
        else
          { $t->_add_cpi_outside_of_root( trailing_cpi => $elt); }

        if( $twig_current)
          { $twig_current->del_twig_current;
            my $parent= $elt->_parent;
            $t->{twig_current}= $parent;
            $parent->set_twig_current;
          }

        $t->$elt_handler( $elt);
      }

  }

sub _trigger_text_handler
  { my ($t) = @_;
    if( my $text_handler= $t->{twig_handlers}->{handlers}->{$TEXT} )
      { local $_= $t->{twig_current};
        $text_handler->( $t, $_) if $_;
      }
  }

# add a comment or pi before the first element
sub _add_cpi_outside_of_root
  { my($t, $type, $elt)= @_; # $type is 'leading_cpi' or 'trailing_cpi'
    $t->{$type} ||= $t->{twig_elt_class}->new( '#CPI');
    # create the node as a child of the current element
    $elt->paste_last_child( $t->{$type});
    return $t;
  }

sub _twig_final
   { # warn " in _twig_final...\n"; # DEBUG handler

    my $p= shift;
    my $t= $p->isa( 'XML::Twig') ? $p : $p->{twig};

    # store trailing data
    if( $t->{extra_data}) { $t->{trailing_cpi_text} = $t->{extra_data}; $t->{extra_data}=''; }
    $t->{trailing_spaces}= $t->{twig_stored_spaces} || '';
    my $s=  $t->{twig_stored_spaces}; $s=~s{\n}{\\n}g;
    if( $t->{twig_stored_spaces}) { my $s=  $t->{twig_stored_spaces}; }

    # restore the selected filehandle if needed
    $t->_set_fh_to_selected_fh();

    $t->_trigger_tdh if( $t->{twig_tdh});

    select $t->{twig_original_selected_fh} if($t->{twig_original_selected_fh}); # probably dodgy

    if( exists $t->{twig_autoflush_data})
      { my @args;
        push @args,  $t->{twig_autoflush_data}->{fh}      if( $t->{twig_autoflush_data}->{fh});
        push @args,  @{$t->{twig_autoflush_data}->{args}} if( $t->{twig_autoflush_data}->{args});
        $t->flush( @args);
        delete $t->{twig_autoflush_data};
        $t->root->delete if $t->root;
      }

    # tries to clean-up (probably not very well at the moment)
    #undef $p->{twig};
    undef $t->{twig_parser};
    delete $t->{twig_parsing};
    @{$t}{ qw( twig_parser twig_parsing _twig_context_stack twig_current) }=();

    return $t;
  }

sub _insert_pcdata
  { my( $t, $string)= @_;
    # create a new PCDATA element
    my $parent= $t->{twig_current};    # always defined
    my $elt;
    if( exists $t->{twig_alt_elt_class})
      { $elt=  $t->{twig_elt_class}->new( $PCDATA);
        $elt->_set_pcdata( $string);
      }
    else
      { $elt= bless( { gi => $XML::Twig::gi2index{$PCDATA}, pcdata => $string }, 'XML::Twig::Elt'); }

    my $prev_sibling= $parent->_last_child;
    if( $prev_sibling)
      { $prev_sibling->set_next_sibling( $elt);
        $elt->set_prev_sibling( $prev_sibling);
      }
    else
      { $parent->set_first_child( $elt); }

    $elt->set_parent( $parent);
    $parent->set_last_child( $elt);
    $t->{twig_stored_spaces}='';
    return $elt;
  }

sub _space_policy
  { my( $t, $gi)= @_;
    my $policy;
    $policy=0 if( $t->{twig_discard_spaces});
    $policy=1 if( $t->{twig_keep_spaces});
    $policy=1 if( $t->{twig_keep_spaces_in}
               && $t->{twig_keep_spaces_in}->{$gi});
    $policy=0 if( $t->{twig_discard_spaces_in}
               && $t->{twig_discard_spaces_in}->{$gi});
    return $policy;
  }

sub _twig_entity
   { # warn " in _twig_entity...\n"; # DEBUG handler
    my( $p, $name, $val, $sysid, $pubid, $ndata, $param)= @_;
    my $t=$p->{twig};

    #{ no warnings; my $base= $p->base; warn "_twig_entity called: expand: '$t->{twig_expand_external_ents}', base: '$base', name: '$name', val: '$val', sysid: '$sysid', pubid: '$pubid', ndata: '$ndata', param: '$param'\n";}

    my $missing_entity=0;

    if( $sysid)
      { if($ndata)
          { if( ! -f _based_filename( $sysid, $p->base)) { $missing_entity= 1; }
          }
        else
          { if( $t->{twig_expand_external_ents})
              { $val= eval { _slurp_uri( $sysid, $p->base) };
                if( ! defined $val)
                  { if( $t->{twig_extern_ent_nofail})
                      { $missing_entity= 1; }
                    else
                      { _croak( "cannot load SYSTEM entity '$name' from '$sysid': $@", 3); }
                  }
              }
          }
      }

    my $ent=XML::Twig::Entity->new( $name, $val, $sysid, $pubid, $ndata, $param);
    if( $missing_entity) { $t->{twig_missing_system_entities}->{$name}= $ent; }

    my $entity_list= $t->entity_list;
    if( $entity_list) { $entity_list->add( $ent); }

    if( $parser_version > 2.27)

lib/XML/Twig.pm  view on Meta::CPAN

        unless( $text)
          { # this version of XML::Parser does not return the text in the *_string method
            # we need to rebuild it
            $text= "<!ELEMENT $name $model>";
          }
        $t->{twig_doctype}->{internal} .= $text;
      }
    return;
  }

sub _twig_attlist
   { # warn " in _twig_attlist...\n"; # DEBUG handler

    my( $p, $gi, $att, $type, $default, $fixed)= @_;
    #warn "in attlist: gi: '$gi', att: '$att', type: '$type', default: '$default', fixed: '$fixed'\n";
    my $t=$p->{twig};
    $t->{twig_dtd}||= {};                      # create dtd if need be
    $t->{twig_dtd}->{$gi}||= {};               # create elt if need be
    #$t->{twig_dtd}->{$gi}->{att}||= {};        # create att if need be
    if( ($parser_version > 2.27) && ($t->{twig_doctype}->{internal}=~ m{(^|>)\s*$}) )
      { my $text= $XML::Twig::Elt::keep_encoding ? $p->original_string : $p->recognized_string;
        unless( $text)
          { # this version of XML::Parser does not return the text in the *_string method
            # we need to rebuild it
            my $att_decl="$att $type";
            $att_decl .= " #FIXED"   if( $fixed);
            $att_decl .= " $default" if( defined $default);
            # 2 cases: there is already an attlist on that element or not
            if( $t->{twig_dtd}->{att}->{$gi})
              { # there is already an attlist, add to it
                $t->{twig_doctype}->{internal}=~ s{(<!ATTLIST\s*$gi )(.*?)\n?>}
                                                  { "$1$2\n" . ' ' x length( $1) . "$att_decl\n>"}es;
              }
            else
              { # create the attlist
                 $t->{twig_doctype}->{internal}.= "<!ATTLIST $gi $att_decl>"
              }
          }
      }
    $t->{twig_dtd}->{att}->{$gi}->{$att}= {} ;
    $t->{twig_dtd}->{att}->{$gi}->{$att}->{type}= $type;
    $t->{twig_dtd}->{att}->{$gi}->{$att}->{default}= $default if( defined $default);
    $t->{twig_dtd}->{att}->{$gi}->{$att}->{fixed}= $fixed;
    return;
  }

sub _twig_default
   { # warn " in _twig_default...\n"; # DEBUG handler

    my( $p, $string)= @_;

    my $t= $p->{twig};

    # we need to process the data in 2 cases: entity, or spaces after the closing tag

    # after the closing tag (no twig_current and root has been created)
    if(  ! $t->{twig_current} && $t->{twig_root} && $string=~ m{^\s+$}m) { $t->{twig_stored_spaces} .= $string; }

    # process only if we have an entity
    if( $string=~ m{^&([^;]*);$})
      { # the entity has to be pure pcdata, or we have a problem
        if( ($p->original_string=~ m{^<}) && ($p->original_string=~ m{>$}) )
          { # string is a tag, entity is in an attribute
            $t->{twig_entities_in_attribute}=1 if( $t->{twig_do_not_escape_amp_in_atts});
          }
        else
          { my $ent;
            if( $t->{twig_keep_encoding})
              { _twig_char( $p, $string);
                $ent= substr( $string, 1, -1);
              }
            else
              { $ent= _twig_insert_ent( $t, $string);
              }

            return $ent;
          }
      }
  }

sub _twig_insert_ent
  {
    my( $t, $string)=@_;

    my $twig_current= $t->{twig_current};

    my $ent=  $t->{twig_elt_class}->new( $ENT);
    $ent->set_ent( $string);

    _add_or_discard_stored_spaces( $t);

    if( $t->{twig_in_pcdata})
      { # create the node as a sibling of the #PCDATA

        $ent->set_prev_sibling( $twig_current);
        $twig_current->set_next_sibling( $ent);
        my $parent= $twig_current->_parent;
        $ent->set_parent( $parent);
        $parent->set_last_child( $ent);
        # the twig_current is now the parent
        $twig_current->del_twig_current;
        $t->{twig_current}= $parent;
        # we left pcdata
        $t->{twig_in_pcdata}=0;
      }
    else
      { # create the node as a child of the current element
        $ent->set_parent( $twig_current);
        if( my $prev_sibling= $twig_current->_last_child)
          { $ent->set_prev_sibling( $prev_sibling);
            $prev_sibling->set_next_sibling( $ent);
          }
        else
          { if( $twig_current) { $twig_current->set_first_child( $ent); } }
        if( $twig_current) { $twig_current->set_last_child( $ent); }
      }

    return $ent;
  }

sub parser
  { return $_[0]->{twig_parser}; }

# returns the declaration text (or a default one)
sub xmldecl
  { my $t= shift;
    return '' unless( $t->{twig_xmldecl} || $t->{output_encoding});
    my $decl_string;
    my $decl= $t->{twig_xmldecl};
    if( $decl)
      { my $version= $decl->{version};
        $decl_string= q{<?xml};
        $decl_string .= qq{ version="$version"};

        # encoding can either have been set (in $decl->{output_encoding})
        # or come from the document (in $decl->{encoding})
        if( $t->{output_encoding})
          { my $encoding= $t->{output_encoding};
            $decl_string .= qq{ encoding="$encoding"};
          }
        elsif( $decl->{encoding})
          { my $encoding= $decl->{encoding};
            $decl_string .= qq{ encoding="$encoding"};
          }

        if( defined( $decl->{standalone}))
          { $decl_string .= q{ standalone="};
            $decl_string .= $decl->{standalone} ? "yes" : "no";
            $decl_string .= q{"};
          }

        $decl_string .= "?>\n";
      }
    else
      { my $encoding= $t->{output_encoding};
        $decl_string= qq{<?xml version="1.0" encoding="$encoding"?>};
      }

    my $output_filter= XML::Twig::Elt::output_filter();
    return $output_filter ? $output_filter->( $decl_string) : $decl_string;
  }

sub set_doctype
  { my( $t, $name, $system, $public, $internal)= @_;

lib/XML/Twig.pm  view on Meta::CPAN

sub dtd_print
  { my $t= shift;
    my $fh=  _is_fh( $_[0])  ? shift : undef;
    if( $fh) { print $fh $t->dtd_text; }
    else     { print $t->dtd_text;     }
    return $t;
  }

# build the subs that call directly expat
BEGIN
  { my @expat_methods= qw( depth in_element within_element context
                           current_line current_column current_byte
                           recognized_string original_string
                           xpcroak xpcarp
                           base current_element element_index
                           xml_escape
                           position_in_context);
    foreach my $method (@expat_methods)
      {
        ## no critic (TestingAndDebugging::ProhibitNoStrict);
        no strict 'refs';
        *{$method}= sub { my $t= shift;
                          _croak( "calling $method after parsing is finished") unless( $t->{twig_parsing});
                          return $t->{twig_parser}->$method(@_);
                        };
      }
  }

sub path
  { my( $t, $gi)= @_;
    if( $t->{twig_map_xmlns})
      { return "/" . join( "/", map { $t->_replace_prefix( $_)} ($t->{twig_parser}->context, $gi)); }
    else
      { return "/" . join( "/", ($t->{twig_parser}->context, $gi)); }
  }

sub finish
  { my $t= shift;
    return $t->{twig_parser}->finish;
  }

# just finish the parse by printing the rest of the document
sub finish_print
  { my( $t, $fh)= @_;
    my $old_fh;
    unless( defined $fh)
      { $t->_set_fh_to_twig_output_fh(); }
    elsif( defined $fh)
      { $old_fh= select $fh;
        $t->{twig_original_selected_fh}= $old_fh if( $old_fh);
      }

    my $p=$t->{twig_parser};
    if( $t->{twig_keep_encoding})
      { $p->setHandlers( %twig_handlers_finish_print); }
    else
      { $p->setHandlers( %twig_handlers_finish_print_original); }
    return $t;
  }

sub set_remove_cdata { return XML::Twig::Elt::set_remove_cdata( @_); }

sub output_filter          { return XML::Twig::Elt::output_filter( @_);          }
sub set_output_filter      { return XML::Twig::Elt::set_output_filter( @_);      }

sub output_text_filter     { return XML::Twig::Elt::output_text_filter( @_);     }
sub set_output_text_filter { return XML::Twig::Elt::set_output_text_filter( @_); }

sub set_input_filter
  { my( $t, $input_filter)= @_;
    my $old_filter= $t->{twig_input_filter};
      if( !$input_filter || isa( $input_filter, 'CODE') )
        { $t->{twig_input_filter}= $input_filter; }
      elsif( $input_filter eq 'latin1')
        {  $t->{twig_input_filter}= latin1(); }
      elsif( $filter{$input_filter})
        {  $t->{twig_input_filter}= $filter{$input_filter}; }
      else
        { _croak( "invalid input filter: $input_filter"); }

      return $old_filter;
    }

sub set_empty_tag_style
  { return XML::Twig::Elt::set_empty_tag_style( @_); }

sub set_pretty_print
  { return XML::Twig::Elt::set_pretty_print( @_); }

sub set_quote
  { return XML::Twig::Elt::set_quote( @_); }

sub set_indent
  { return XML::Twig::Elt::set_indent( @_); }

sub set_keep_atts_order
  { shift; return XML::Twig::Elt::set_keep_atts_order( @_); }

sub keep_atts_order
  { return XML::Twig::Elt::keep_atts_order( @_); }

sub set_do_not_escape_amp_in_atts
  { return XML::Twig::Elt::set_do_not_escape_amp_in_atts( @_); }

# save and restore package globals (the ones in XML::Twig::Elt)
# should probably return the XML::Twig object itself, but instead
# returns the state (as a hashref) for backward compatibility
sub save_global_state
  { my $t= shift;
    return $t->{twig_saved_state}= XML::Twig::Elt::global_state();
  }

sub restore_global_state
  { my $t= shift;
    XML::Twig::Elt::set_global_state( $t->{twig_saved_state});
  }

sub global_state
  { return XML::Twig::Elt::global_state(); }

sub set_global_state

lib/XML/Twig.pm  view on Meta::CPAN

    *sort_children_by_value= *sort_children_on_value;

    *has_atts= *att_nb;

    # imports from XML::Twig
    *_is_fh= *XML::Twig::_is_fh;

    # XML::XPath compatibility
    *string_value       = *text;
    *toString           = *sprint;
    *getName            = *gi;
    *getRootNode        = *twig;
    *getNextSibling     = *_next_sibling;
    *getPreviousSibling = *_prev_sibling;
    *isElementNode      = *is_elt;
    *isTextNode         = *is_text;
    *isPI               = *is_pi;
    *isPINode           = *is_pi;
    *isProcessingInstructionNode= *is_pi;
    *isComment          = *is_comment;
    *isCommentNode      = *is_comment;
    *getTarget          = *target;
    *getFirstChild      = *_first_child;
    *getLastChild      = *_last_child;

    # try using weak references
    # test whether we can use weak references
    { local $SIG{__DIE__};
    ## no critic (ProhibitStringyEval)
      if( eval 'require Scalar::Util' && defined( &Scalar::Util::weaken) )
        { import Scalar::Util qw(weaken); }
      elsif( eval 'require WeakRef')
        { import WeakRef; }
    }
}

# can be called as XML::Twig::Elt->new( [[$gi, $atts, [@content]])
# - gi is an optional gi given to the element
# - $atts is a hashref to attributes for the element
# - @content is an optional list of text and elements that will
#   be inserted under the element
sub new
  { my $class= shift;
    $class= ref $class || $class;
    my $elt  = {};
    bless ($elt, $class);

    return $elt unless @_;

    if( @_ == 1 && $_[0]=~ m{^\s*<}) { return $class->parse( @_); }

    # if a gi is passed then use it
    my $gi= shift;
    $elt->set_gi( $gi);

    my $atts= ref $_[0] eq 'HASH' ? shift : undef;

    if( $atts && defined $atts->{$CDATA})
      { delete $atts->{$CDATA};

        my $cdata= $class->new( $CDATA => @_);
        return $class->new( $gi, $atts, $cdata);
      }

    if( $gi eq $PCDATA)
      { if( grep { ref $_ } @_) { croak "element $PCDATA can only be created from text"; }
        $elt->_set_pcdata( join '', @_);
      }
    elsif( $gi eq $ENT)
      { $elt->set_ent( shift); }
    elsif( $gi eq $CDATA)
      { if( grep { ref $_ } @_) { croak "element $CDATA can only be created from text"; }
        $elt->_set_cdata( join '', @_);
      }
    elsif( $gi eq $COMMENT)
      { if( grep { ref $_ } @_) { croak "element $COMMENT can only be created from text"; }
        $elt->_set_comment( join '', @_);
      }
    elsif( $gi eq $PI)
      { if( grep { ref $_ } @_) { croak "element $PI can only be created from text"; }
        $elt->_set_pi( shift, join '', @_);
      }
    else
      { # the rest of the arguments are the content of the element
        if( @_)
          { $elt->set_content( @_); }
        else
          { $elt->set_empty( 1);    }
      }

    if( $atts)
      { # the attribute hash can be used to pass the asis status
        if( defined $atts->{$ASIS})  { $elt->set_asis(  $atts->{$ASIS} ); delete $atts->{$ASIS};  }
        if( defined $atts->{$EMPTY}) { $elt->set_empty( $atts->{$EMPTY}); delete $atts->{$EMPTY}; }
        if( keys %$atts) { $elt->set_atts( $atts); }
        $elt->_set_id( $atts->{$ID}) if( $atts->{$ID});
      }

    return $elt;
  }

# optimized version of $elt->new( PCDATA, $text);
sub _new_pcdata
  { my $class= $_[0];
    $class= ref $class || $class;
    my $elt  = {};
    bless $elt, $class;
    $elt->set_gi( $PCDATA);
    $elt->_set_pcdata( $_[1]);
    return $elt;
  }

# this function creates an XM:::Twig::Elt from a string
# it is quite clumsy at the moment, as it just creates a
# new twig then returns its root
# there might also be memory leaks there
# additional arguments are passed to new XML::Twig
sub parse
  { my $class= shift;
    if( ref( $class)) { $class= ref( $class); }
    my $string= shift;
    my %args= @_;
    my $t= XML::Twig->new(%args);
    $t->parse( $string);
    my $elt= $t->root;
    # clean-up the node
    delete $elt->{twig};         # get rid of the twig data
    delete $elt->{twig_current}; # better get rid of this too
    if( $t->{twig_id_list}) { $elt->{twig_id_list}= $t->{twig_id_list}; }
    $elt->cut;
    undef $t->{twig_root};
    return $elt;
  }

sub set_inner_xml
  { my( $elt, $xml, @args)= @_;
    my $new_elt= $elt->parse( "<dummy>$xml</dummy>", @args);
    $elt->cut_children;
    $new_elt->paste_first_child( $elt);
    $new_elt->erase;
    return $elt;
  }

sub set_outer_xml
  { my( $elt, $xml, @args)= @_;
    my $new_elt= $elt->parse( "<dummy>$xml</dummy>", @args);
    $elt->cut_children;
    $new_elt->replace( $elt);
    $new_elt->erase;
    return $new_elt;
  }

sub set_inner_html
  { my( $elt, $html)= @_;
    my $t= XML::Twig->new->parse_html( "<html>$html</html>");
    my $new_elt= $t->root;
    if( $elt->tag eq 'head')
      { $new_elt->first_child( 'head')->unwrap;
        $new_elt->first_child( 'body')->cut;
      }
    elsif( $elt->tag ne 'html')
      { $new_elt->first_child( 'head')->cut;
        $new_elt->first_child( 'body')->unwrap;
      }
    $new_elt->cut;
    $elt->cut_children;
    $new_elt->paste_first_child( $elt);
    $new_elt->erase;
    return $elt;

lib/XML/Twig.pm  view on Meta::CPAN


sub _current_ns_prefix_map
  { my( $elt)= shift;
    my $map;
    while( $elt)
      { foreach my $att ($elt->att_names)
          { my $prefix= $att eq 'xmlns'        ? '#default'
                      : $att=~ m{^xmlns:(.*)$} ? $1
                      : next
                      ;
            if( ! exists $map->{$prefix}) { $map->{$prefix}= $elt->att( $att); }
          }
        $elt= $elt->_parent || $elt->former_parent;
      }
    return $map;
  }

sub set_ns_decl
  { my( $elt, $uri, $prefix)= @_;
    my $ns_att=  $prefix ? "xmlns:$prefix" : 'xmlns';
    $elt->set_att( $ns_att => $uri);
    return $elt;
  }

sub set_ns_as_default
  { my( $root, $uri)= @_;
    my @ns_decl_to_remove;
    foreach my $elt ($root->descendants_or_self)
      { if( $elt->_ns_prefix && $elt->namespace eq $uri)
          { $elt->set_tag( $elt->local_name); }
        # store any namespace declaration for that uri
        foreach my $ns_decl (grep { $_=~ m{xmlns(:|$)} && $elt->att( $_) eq $uri } $elt->att_names)
          { push @ns_decl_to_remove, [$elt, $ns_decl]; }
      }
    $root->set_ns_decl( $uri);
    # now remove the ns declarations (if done earlier then descendants of an element with the ns declaration
    # are not considered being in the namespace
    foreach my $ns_decl_to_remove ( @ns_decl_to_remove)
      { my( $elt, $ns_decl)= @$ns_decl_to_remove;
        $elt->del_att( $ns_decl);
      }

    return $root;
  }

# return #ELT for an element and #PCDATA... for others
sub get_type
  { my $gi_nb= $_[0]->{gi}; # the number, not the string
    return $ELT if( $gi_nb >= $XML::Twig::SPECIAL_GI);
    return $_[0]->gi;
  }

# return the gi if it's a "real" element, 0 otherwise
sub is_elt
  { if(  $_[0]->{gi} >=  $XML::Twig::SPECIAL_GI)
     { return $_[0]->gi; }
    else
      { return 0; }
  }

sub is_pcdata
  { my $elt= shift;
    return (exists $elt->{'pcdata'});
  }

sub is_cdata
  { my $elt= shift;
    return (exists $elt->{'cdata'});
  }

sub is_pi
  { my $elt= shift;
    return (exists $elt->{'target'});
  }

sub is_comment
  { my $elt= shift;
    return (exists $elt->{'comment'});
  }

sub is_ent
  { my $elt= shift;
    return (exists $elt->{ent} || $elt->{ent_name});
  }

sub is_text
  { my $elt= shift;
    return (exists( $elt->{'pcdata'}) || (exists $elt->{'cdata'}));
  }

sub is_empty
  { return $_[0]->{empty} || 0; }

sub set_empty
  { $_[0]->{empty}= defined( $_[1]) ? $_[1] : 1; return $_[0]; }

sub set_not_empty
  { delete $_[0]->{empty} if( $_[0]->is_empty); return $_[0]; }

sub set_asis
  { my $elt=shift;

    foreach my $descendant ($elt, $elt->_descendants )
      { $descendant->{asis}= 1;
        if( $descendant->is_cdata)
          { $descendant->set_gi( $PCDATA);
            $descendant->_set_pcdata( $descendant->cdata);
          }

      }
    return $elt;
  }

sub set_not_asis
  { my $elt=shift;
    foreach my $descendant ($elt, $elt->descendants)
      { delete $descendant->{asis} if $descendant->{asis};}
    return $elt;
  }

sub is_asis
  { return $_[0]->{asis}; }

sub closed
  { my $elt= shift;
    my $t= $elt->twig || return;
    my $curr_elt= $t->{twig_current};
    return 1 unless( $curr_elt);
    return $curr_elt->in( $elt);
  }

sub set_pcdata
  { my( $elt, $pcdata)= @_;

    if( $elt->_extra_data_in_pcdata)
      { _try_moving_extra_data( $elt, $pcdata);
      }
    $elt->{pcdata}= $pcdata;
    return $elt;
  }

sub _extra_data_in_pcdata      { return $_[0]->{extra_data_in_pcdata}; }
sub _set_extra_data_in_pcdata  { $_[0]->{extra_data_in_pcdata}= $_[1]; return $_[0]; }
sub _del_extra_data_in_pcdata  { delete $_[0]->{extra_data_in_pcdata}; return $_[0]; }
sub _unshift_extra_data_in_pcdata
    { my $e= shift;
      $e->{extra_data_in_pcdata}||=[];
      unshift @{$e->{extra_data_in_pcdata}}, { text => shift(), offset => shift() };
    }
sub _push_extra_data_in_pcdata
  { my $e= shift;
    $e->{extra_data_in_pcdata}||=[];
    push @{$e->{extra_data_in_pcdata}}, { text => shift(), offset => shift() };
  }

sub _extra_data_before_end_tag     { return $_[0]->{extra_data_before_end_tag} || ''; }
sub _set_extra_data_before_end_tag { $_[0]->{extra_data_before_end_tag}= $_[1]; return $_[0]}
sub _del_extra_data_before_end_tag { delete $_[0]->{extra_data_before_end_tag}; return $_[0]}
sub _prefix_extra_data_before_end_tag
  { my( $elt, $data)= @_;
    if($elt->{extra_data_before_end_tag})
      { $elt->{extra_data_before_end_tag}= $data . $elt->{extra_data_before_end_tag}; }
    else
      { $elt->{extra_data_before_end_tag}= $data; }
    return $elt;
  }

# internal, in cases where we know there is no extra_data (inlined anyway!)
sub _set_pcdata { $_[0]->{pcdata}= $_[1]; }

# try to figure out if we can keep the extra_data around
sub _try_moving_extra_data
  { my( $elt, $modified)=@_;
    my $initial= $elt->{pcdata};
    my $cpis= $elt->_extra_data_in_pcdata;

    if( (my $offset= index( $modified, $initial)) != -1)
      { # text has been added
        foreach (@$cpis) { $_->{offset}+= $offset; }
      }
    elsif( ($offset= index( $initial, $modified)) != -1)
      { # text has been cut
        my $len= length( $modified);
        foreach my $cpi (@$cpis) { $cpi->{offset} -= $offset; }
        $elt->_set_extra_data_in_pcdata( [ grep { $_->{offset} >= 0 && $_->{offset} < $len } @$cpis ]);
      }
    else
      {    _match_extra_data_words( $elt, $initial, $modified)
        || _match_extra_data_chars( $elt, $initial, $modified)
        || $elt->_del_extra_data_in_pcdata;
      }
  }

sub _match_extra_data_words
  { my( $elt, $initial, $modified)= @_;
    my @initial= split /\b/, $initial;
    my @modified= split /\b/, $modified;

    return _match_extra_data( $elt, length( $initial), \@initial, \@modified);
  }

sub _match_extra_data_chars
  { my( $elt, $initial, $modified)= @_;
    my @initial= split //, $initial;
    my @modified= split //, $modified;

    return _match_extra_data( $elt, length( $initial), \@initial, \@modified);
  }

sub _match_extra_data
  { my( $elt, $length, $initial, $modified)= @_;

    my $cpis= $elt->_extra_data_in_pcdata;

    if( @$initial <= @$modified)
      {
        my( $ok, $positions, $offsets)= _pos_offset( $initial, $modified);
        if( $ok)
          { my $offset=0;
            my $pos= shift @$positions;
            foreach my $cpi (@$cpis)
              { while( $cpi->{offset} >= $pos)
                  { $offset= shift @$offsets;
                    $pos= shift @$positions || $length +1;
                  }
                $cpi->{offset} += $offset;
              }
            return 1;
          }
      }
    else
      { my( $ok, $positions, $offsets)= _pos_offset( $modified, $initial);
        if( $ok)
          { #print STDERR "pos:    ", join( ':', @$positions), "\n",
            #             "offset: ", join( ':', @$offsets), "\n";
            my $offset=0;
            my $pos= shift @$positions;
            my $prev_pos= 0;

            foreach my $cpi (@$cpis)
              { while( $cpi->{offset} >= $pos)
                  { $offset= shift @$offsets;
                    $prev_pos= $pos;
                    $pos= shift @$positions || $length +1;
                  }
                $cpi->{offset} -= $offset;
                if( $cpi->{offset} < $prev_pos) { delete $cpi->{text}; }
              }
            $elt->_set_extra_data_in_pcdata( [ grep { exists $_->{text} } @$cpis ]);
            return 1;
          }
      }
    return 0;
  }

sub _pos_offset
  { my( $short, $long)= @_;
    my( @pos, @offset);
    my( $s_length, $l_length)=(0,0);
    while (@$short)
      { my $s_word= shift @$short;
        my $l_word= shift @$long;
        if( $s_word ne $l_word)
          { while( @$long && $s_word ne $l_word)
              { $l_length += length( $l_word);
                $l_word= shift @$long;
              }
            if( !@$long && $s_word ne $l_word) { return 0; }
            push @pos, $s_length;
            push @offset, $l_length - $s_length;
          }
        my $length= length( $s_word);
        $s_length += $length;
        $l_length += $length;
      }
    return( 1, \@pos, \@offset);
  }

sub append_pcdata
  { $_[0]->{'pcdata'}.= $_[1];
    return $_[0];
  }

sub pcdata        { return $_[0]->{pcdata}; }

sub append_extra_data
  {  $_[0]->{extra_data}.= $_[1];
     return $_[0];
  }

sub set_extra_data
  { $_[0]->{extra_data}= $_[1];
    return $_[0];
  }
sub extra_data { return $_[0]->{extra_data} || ''; }

sub set_target
  { my( $elt, $target)= @_;
    $elt->{target}= $target;
    return $elt;
  }
sub target { return $_[0]->{target}; }

sub set_data
  { $_[0]->{'data'}= $_[1];
    return $_[0];
  }
sub data { return $_[0]->{data}; }

sub set_pi
  { my $elt= shift;
    unless( $elt->{gi} == $XML::Twig::gi2index{$PI})
      { $elt->cut_children;
        $elt->set_gi( $PI);
      }
    return $elt->_set_pi( @_);
  }

sub _set_pi
  { $_[0]->set_target( $_[1]);
    $_[0]->set_data( $_[2]);
    return $_[0];
  }

sub pi_string { my $string= $PI_START . $_[0]->target;
                my $data= $_[0]->data;
                if( defined( $data) && $data ne '') { $string .= " $data"; }
                $string .= $PI_END ;
                return $string;
              }

sub set_comment
  { my $elt= shift;
    unless( $elt->{gi} == $XML::Twig::gi2index{$COMMENT})
      { $elt->cut_children;
        $elt->set_gi( $COMMENT);
      }
    $elt->_set_comment( $_[0]);
    return $elt;
  }

sub _set_comment   { $_[0]->{comment}= $_[1]; return $_[0]; }
sub comment        { return $_[0]->{comment}; }
sub comment_string { return $COMMENT_START . _comment_escaped_string( $_[0]->comment) . $COMMENT_END; }
# comments cannot start or end with
sub _comment_escaped_string
  { my( $c)= @_;
    $c=~ s{^-}{ -};
    $c=~ s{-$}{- };
    $c=~ s{--}{- -}g;
    return $c;
  }

sub set_ent  { $_[0]->{ent}= $_[1]; return $_[0]; }
sub ent      { return $_[0]->{ent}; }
sub ent_name { return substr( $_[0]->ent, 1, -1);}

sub set_cdata
  { my $elt= shift;
    unless( $elt->{gi} == $XML::Twig::gi2index{$CDATA})
      { $elt->cut_children;
        $elt->insert_new_elt( first_child => $CDATA, @_);
        return $elt;
      }
    $elt->_set_cdata( $_[0]);
    return $_[0];
  }

sub _set_cdata
  { $_[0]->{cdata}= $_[1];
    return $_[0];
  }

sub append_cdata
  { $_[0]->{cdata}.= $_[1];
    return $_[0];
  }
sub cdata { return $_[0]->{cdata}; }

sub contains_only_text
  { my $elt= shift;
    return 0 unless $elt->is_elt;
    foreach my $child ($elt->_children)
      { return 0 if $child->is_elt; }
    return $elt;
  }

sub contains_only
  { my( $elt, $exp)= @_;
    my @children= $elt->_children;
    foreach my $child (@children)
      { return 0 unless $child->is( $exp); }
    return @children || 1;
  }

sub contains_a_single
  { my( $elt, $exp)= @_;
    my $child= $elt->_first_child or return 0;
    return 0 unless $child->passes( $exp);
    return 0 if( $child->_next_sibling);
    return $child;
  }

sub root
  { my $elt= shift;
    while( $elt->_parent) { $elt= $elt->_parent; }
    return $elt;
  }

sub _root_through_cut
  { my $elt= shift;
    while( $elt->_parent || $elt->former_parent) { $elt= $elt->_parent || $elt->former_parent; }
    return $elt;
  }

sub twig
  { my $elt= shift;
    my $root= $elt->root;
    return $root->{twig};
  }

sub _twig_through_cut
  { my $elt= shift;
    my $root= $elt->_root_through_cut;
    return $root->{twig};
  }

# used for navigation
# returns undef or the element, depending on whether $elt passes $cond
# $cond can be
# - empty: the element passes the condition
# - ELT ('#ELT'): the element passes the condition if it is a "real" element
# - TEXT ('#TEXT'): the element passes if it is a CDATA or PCDATA element
# - a string with an XPath condition (only a subset of XPath is actually
#   supported).
# - a regexp: the element passes if its gi matches the regexp
# - a code ref: the element passes if the code, applied on the element,
#   returns true

lib/XML/Twig.pm  view on Meta::CPAN

        $elt->_move_extra_data_after_erase;
        my @children= $elt->_children;
        if( @children)
          {
            # elt has children, move them up

            # the first child may need to be merged with a previous text
            my $first_child= shift @children;
            $first_child->move( before => $elt);
            my $prev= $first_child->prev_sibling;
            if( $prev && $prev->is_text && ($first_child->gi eq $prev->gi) )
              { $prev->merge_text( $first_child); }

            # move the rest of the children
            foreach my $child (@children)
              { $child->move( before => $elt); }

            # now the elt had no child, delete it
            $elt->delete;

            # now see if we need to merge the last child with the next element
            my $last_child= $children[-1] || $first_child; # if no last child, then it's also the first child
            my $next= $last_child->next_sibling;
            if( $next && $next->is_text && ($last_child->gi eq $next->gi) )
              { $last_child->merge_text( $next); }

            # if parsing and have now a PCDATA text, mark so we can normalize later on if need be
            if( $parent->{twig_current} && $last_child->is_text) {  $parent->{twig_to_be_normalized}=1; }
          }
       else
         { # no children, just cut the elt
           $elt->delete;
         }
      }
    else
      { # trying to erase the root (of a twig or of a cut/new element)
        my @children= $elt->_children;
        unless( @children == 1)
          { croak "can only erase an element with no parent if it has a single child"; }
        $elt->_move_extra_data_after_erase;
        my $child= shift @children;
        $child->set_parent( undef);
        my $twig= $elt->twig;
        $twig->set_root( $child);
      }

    return $elt;

  }

sub _move_extra_data_after_erase
  { my( $elt)= @_;
    # extra_data
    if( my $extra_data= $elt->{extra_data})
      { my $target= $elt->_first_child || $elt->_next_sibling;
        if( $target)
          {
            if( $target->is( $ELT))
              { $target->set_extra_data( $extra_data . ($target->extra_data || '')); }
            elsif( $target->is( $TEXT))
              { $target->_unshift_extra_data_in_pcdata( $extra_data, 0); }  # TO CHECK
          }
        else
          { my $parent= $elt->parent; # always exists or the erase cannot be performed
            $parent->_prefix_extra_data_before_end_tag( $extra_data);
          }
      }

     # extra_data_before_end_tag
    if( my $extra_data= $elt->_extra_data_before_end_tag)
      { if( my $target= $elt->_next_sibling)
          { if( $target->is( $ELT))
              { $target->set_extra_data( $extra_data . ($target->extra_data || '')); }
            elsif( $target->is( $TEXT))
              {
                $target->_unshift_extra_data_in_pcdata( $extra_data, 0);
             }
          }
        elsif( my $parent= $elt->parent)
          { $parent->_prefix_extra_data_before_end_tag( $extra_data); }
       }

    return $elt;

  }
BEGIN
  { my %method= ( before      => \&paste_before,
                  after       => \&paste_after,
                  first_child => \&paste_first_child,
                  last_child  => \&paste_last_child,
                  within      => \&paste_within,
        );

    # paste elt somewhere around ref
    # pos can be first_child (default), last_child, before, after or within
    sub paste ## no critic (Subroutines::ProhibitNestedSubs);
      { my $elt= shift;
        if( $elt->_parent)
          { croak "cannot paste an element that belongs to a tree"; }
        my $pos;
        my $ref;
        if( ref $_[0])
          { $pos= 'first_child';
            croak "wrong argument order in paste, should be $_[1] first" if($_[1]);
          }
        else
          { $pos= _op_position(shift); }

        if( my $method= $method{$pos})
          {
            unless( ref( $_[0]) && isa( $_[0], 'XML::Twig::Elt'))
              { if( ! defined( $_[0]))
                  { croak "missing target in paste"; }
                elsif( ! ref( $_[0]))
                  { croak "wrong target type in paste (not a reference), should be XML::Twig::Elt or a subclass"; }
                else
                  { my $ref= ref $_[0];
                    croak "wrong target type in paste: '$ref', should be XML::Twig::Elt or a subclass";
                  }
              }
            $ref= $_[0];
            # check here so error message lists the caller file/line
            if( !$ref->_parent && ($pos=~ m{^(before|after)$}) && !$elt->is_pi && !$elt->is_comment)
              { croak "cannot paste $1 root"; }
            $elt->$method( @_);
          }
        else
          { croak "tried to paste in wrong position '$pos', allowed positions  are "
            . _allowed_positions() . ".\n";
          }
        if( (my $ids= $elt->{twig_id_list}) && (my $t= $ref->twig) )
          { $t->{twig_id_list}||={};
            foreach my $id (keys %$ids)
              { $t->{twig_id_list}->{$id}= $ids->{$id};
                if( $XML::Twig::weakrefs) { weaken( $t->{twig_id_list}->{$id}); }
              }

lib/XML/Twig.pm  view on Meta::CPAN

  }

sub _text_with_vars
  { my( $elt, $options)= @_;
    my $text;
    if( $options->{var})
      { $text= _replace_vars_in_text( $elt->text, $options);
        $elt->_store_var( $options);
      }
     else
      { $text= $elt->text; }
    return $text;
  }

sub _normalize_space
  { my $text= shift;
    $text=~ s{\s+}{ }sg;
    $text=~ s{^\s}{};
    $text=~ s{\s$}{};
    return $text;
  }

sub att_nb
  { return 0 unless( my $atts= $_[0]->atts);
    return scalar keys %$atts;
  }

sub has_no_atts
  { return 1 unless( my $atts= $_[0]->atts);
    return scalar keys %$atts ? 0 : 1;
  }

sub _replace_vars_in_text
  { my( $text, $options)= @_;

    $text=~ s{($options->{var_regexp})}
             { if( defined( my $value= $options->{var_values}->{$2}))
                 { $value }
               else
                 { warn "unknown variable $2\n";
                   $1
                 }
             }gex;
    return $text;
  }

sub _store_var
  { my( $elt, $options)= @_;
    if( defined (my $var_name= $elt->att( $options->{var})))
       { $options->{var_values}->{$var_name}= $elt->text;
       }
  }

# split a text element at a given offset
sub split_at
  { my( $elt, $offset)= @_;
    my $text_elt= $elt->is_text ? $elt : $elt->first_child( $TEXT) || return '';
    my $string= $text_elt->text;
    my $left_string= substr( $string, 0, $offset);
    my $right_string= substr( $string, $offset);
    $text_elt->set_pcdata( $left_string);
    my $new_elt= $elt->new( $elt->gi, $right_string);
    $new_elt->paste( after => $elt);
    return $new_elt;
  }

# split an element or its text descendants into several, in place
# all elements (new and untouched) are returned
sub split
  { my $elt= shift;
    my @text_chunks;
    my @result;
    if( $elt->is_text) { @text_chunks= ($elt); }
    else               { @text_chunks= $elt->descendants( $TEXT); }
    foreach my $text_chunk (@text_chunks)
      { push @result, $text_chunk->_split( 1, @_); }
    return @result;
  }

# split an element or its text descendants into several, in place
# created elements (those which match the regexp) are returned
sub mark
  { my $elt= shift;
    my @text_chunks;
    my @result;
    if( $elt->is_text) { @text_chunks= ($elt); }
    else               { @text_chunks= $elt->descendants( $TEXT); }
    foreach my $text_chunk (@text_chunks)
      { push @result, $text_chunk->_split( 0, @_); }
    return @result;
  }

# split a single text element
# return_all defines what is returned: if it is true
# only returns the elements created by matches in the split regexp
# otherwise all elements (new and untouched) are returned
{

  sub _split
    { my $elt= shift;
      my $return_all= shift;
      my $regexp= shift;
      my @tags;

      while( @_)
        { my $tag= shift();
          if( ref $_[0])
            { push @tags, { tag => $tag, atts => shift }; }
          else
            { push @tags, { tag => $tag }; }
        }

      unless( @tags) { @tags= { tag => $elt->_parent->gi }; }

      my @result;                                 # the returned list of elements
      my $text= $elt->text;
      my $gi= $elt->gi;

      # 2 uses: if split matches then the first substring reuses $elt
      #         once a split has occurred then the last match needs to be put in
      #         a new element

lib/XML/Twig.pm  view on Meta::CPAN

  sub _replace_var
    { my( $string, @var)= @_;
      unshift @var, undef;
      $string=~ s{\$(\d)}{$var[$1]}g;
      return $string;
    }

  sub _install_replace_sub
    { my $replace_exp= shift;
      my @item= split m{(&e[ln]t\s*\([^)]*\))}, $replace_exp;
      my $sub= q{ my( $match, @var)= @_; my $new; my $last_inserted=$match;};
      my( $gi, $exp);
      foreach my $item (@item)
        { next if ! length $item;
          if(    $item=~ m{^&elt\s*\(([^)]*)\)})
            { $exp= $1; }
          elsif( $item=~ m{^&ent\s*\(\s*([^\s)]*)\s*\)})
            { $exp= " '#ENT' => $1"; }
          else
            { $exp= qq{ '#PCDATA' => "$item"}; }
          $exp=~ s{\$(\d)}{my $i= $1-1; "\$var[$i]"}eg; # replace references to matches
          $sub.= qq{ \$new= \$match->new( $exp); };
          $sub .= q{ $new->paste( after => $last_inserted); $last_inserted=$new;};
        }
      $sub .= q{ $match->delete; };
      #$sub=~ s/;/;\n/g; warn "subs: $sub";
      my $coderef= eval "sub { $NO_WARNINGS; $sub }"; ## no critic (ProhibitStringyEval)
      if( $@) {
          my $msg = "invalid replacement expression $replace_exp: " . $@;
          if( $@ =~ m{Global symbol .* requires explicit package name} )
            { my $suggested = $replace_exp;
              $suggested =~ s{\$(\d)}{\\\$$1}g;
              $msg = join "\n    ",
                  $msg,
                  "the problem seems to be that the replacement expression is a single-quoted string".
                  "that includes variables. Those need to be expanded.",
                  "ie replace the following:",
                  "    '$replace_exp'",
                  "with:",
                  "    qq{$suggested}",
                  ;
            }
          croak $msg;
        }
      return $coderef;
    }

  }

sub merge_text
  { my( $e1, $e2)= @_;
    croak "invalid merge: can only merge 2 elements"
        unless( isa( $e2, 'XML::Twig::Elt'));
    croak "invalid merge: can only merge 2 text elements"
        unless( $e1->is_text && $e2->is_text && ($e1->gi eq $e2->gi));

    my $t1_length= length( $e1->text);

    $e1->set_text( $e1->text . $e2->text);

    if( my $extra_data_in_pcdata= $e2->_extra_data_in_pcdata)
      { foreach my $data (@$extra_data_in_pcdata) { $e1->_push_extra_data_in_pcdata( $data->{text}, $data->{offset} + $t1_length); } }

    $e2->delete;

    return $e1;
  }

sub merge
  { my( $e1, $e2)= @_;
    my @e2_children= $e2->_children;
    if(     $e1->_last_child && $e1->_last_child->is_pcdata
        &&  @e2_children && $e2_children[0]->is_pcdata
      )
      { my $t1_length= length( $e1->_last_child->{pcdata});
        my $child1= $e1->_last_child;
        my $child2= shift @e2_children;
        $child1->{pcdata} .= $child2->{pcdata};

        my $extra_data= $e1->_extra_data_before_end_tag . $e2->extra_data;

        if( $extra_data)
          { $e1->_del_extra_data_before_end_tag;
            $child1->_push_extra_data_in_pcdata( $extra_data, $t1_length);
          }

        if( my $extra_data_in_pcdata= $child2->_extra_data_in_pcdata)
          { foreach my $data (@$extra_data_in_pcdata) { $child1->_push_extra_data_in_pcdata( $data->{text}, $data->{offset} + $t1_length); } }

        if( my $extra_data_before_end_tag= $e2->_extra_data_before_end_tag)
          { $e1->_set_extra_data_before_end_tag( $extra_data_before_end_tag); }
      }

    foreach my $e (@e2_children) { $e->move( last_child => $e1); }

    $e2->delete;
    return $e1;
  }

# recursively copy an element and returns the copy (can be huge and long)
sub copy
  { my $elt= shift;
    my $copy= $elt->new( $elt->gi);

    if( $elt->extra_data) { $copy->set_extra_data( $elt->extra_data); }
    if( $elt->_extra_data_before_end_tag) { $copy->_set_extra_data_before_end_tag( $elt->_extra_data_before_end_tag); }

    if( $elt->is_asis)   { $copy->set_asis; }

    if( $elt->is_pcdata)
      { $copy->set_pcdata( $elt->pcdata);
        if( $elt->_extra_data_in_pcdata) { $copy->_set_extra_data_in_pcdata( $elt->_extra_data_in_pcdata); }
      }
    elsif( $elt->is_cdata)
      { $copy->_set_cdata( $elt->cdata);
        if( $elt->_extra_data_in_pcdata) { $copy->_set_extra_data_in_pcdata( $elt->_extra_data_in_pcdata); }
      }
    elsif( $elt->is_pi)
      { $copy->_set_pi( $elt->target, $elt->data); }
    elsif( $elt->is_comment)
      { $copy->_set_comment( $elt->comment); }
    elsif( $elt->is_ent)
      { $copy->set_ent( $elt->ent); }
    else
      { my @children= $elt->_children;
        if( my $atts= $elt->atts)
          { my %atts;
            tie %atts, 'Tie::IxHash' if (keep_atts_order());
            %atts= %{$atts}; # we want to do a real copy of the attributes
            $copy->set_atts( \%atts);
          }
        foreach my $child (@children)
          { my $child_copy= $child->copy;
            $child_copy->paste( 'last_child', $copy);
          }
      }
    # save links to the original location, which can be convenient and is used for namespace resolution
    foreach my $link ( qw(parent prev_sibling next_sibling) )
      { $copy->{former}->{$link}= $elt->{$link};
        if( $XML::Twig::weakrefs) { weaken( $copy->{former}->{$link}); }
      }

    $copy->set_empty( $elt->is_empty);

    return $copy;
  }

sub delete
  { my $elt= shift;
    $elt->cut;
    $elt->DESTROY unless $XML::Twig::weakrefs;
    return undef;
  }

sub __destroy
  { my $elt= shift;
    return if( $XML::Twig::weakrefs);
    my $t= shift || $elt->twig; # optional argument, passed in recursive calls

    foreach( @{[$elt->_children]}) { $_->DESTROY( $t); }

    # the id reference needs to be destroyed
    # lots of tests to avoid warnings during the cleanup phase
    $elt->del_id( $t) if( $ID && $t && defined( $elt->{att}) && exists( $elt->{att}->{$ID}));
    if( $elt->{former}) { foreach (keys %{$elt->{former}}) { delete $elt->{former}->{$_}; } delete $elt->{former}; }
    foreach (qw( keys %$elt)) { delete $elt->{$_}; }
    undef $elt;
  }

BEGIN
{ sub set_destroy { if( $XML::Twig::weakrefs) { undef *DESTROY } else { *DESTROY= *__destroy; } }
  set_destroy();
}

# ignores the element
sub ignore
  { my $elt= shift;
    my $t= $elt->twig;
    $t->ignore( $elt, @_);
  }

BEGIN {
  my $pretty                    = 0;
  my $quote                     = '"';
  my $INDENT                    = '  ';
  my $empty_tag_style           = 0;
  my $remove_cdata              = 0;
  my $keep_encoding             = 0;
  my $expand_external_entities  = 0;
  my $keep_atts_order           = 0;
  my $do_not_escape_amp_in_atts = 0;
  my $WRAP                      = '80';
  my $REPLACED_ENTS             = qq{&<};

  my ($NSGMLS, $NICE, $INDENTED, $INDENTEDCT, $INDENTEDC, $WRAPPED, $RECORD1, $RECORD2, $INDENTEDA)= (1..9);
  my %KEEP_TEXT_TAG_ON_ONE_LINE= map { $_ => 1 } ( $INDENTED, $INDENTEDCT, $INDENTEDC, $INDENTEDA, $WRAPPED);
  my %WRAPPED =  map { $_ => 1 } ( $WRAPPED, $INDENTEDA, $INDENTEDC);

  my %pretty_print_style=
    ( none       => 0,          # no added \n
      nsgmls     => $NSGMLS,    # nsgmls-style, \n in tags
      # below this line styles are UNSAFE (the generated XML can be well-formed but invalid)
      nice       => $NICE,      # \n after open/close tags except when the
                                # element starts with text
      indented   => $INDENTED,  # nice plus indented
      indented_close_tag   => $INDENTEDCT,  # nice plus indented
      indented_c => $INDENTEDC, # slightly more compact than indented (closing
                                # tags are on the same line)
      wrapped    => $WRAPPED,   # text is wrapped at column
      record_c   => $RECORD1,   # for record-like data (compact)
      record     => $RECORD2,   # for record-like data  (not so compact)
      indented_a => $INDENTEDA, # nice, indented, and with attributes on separate
                                # lines as the nsgmls style, as well as wrapped
                                # lines - to make the xml friendly to line-oriented tools
      cvs        => $INDENTEDA, # alias for indented_a
    );

  my ($HTML, $EXPAND)= (1..2);
  my %empty_tag_style=
    ( normal => 0,        # <tag/>
      html   => $HTML,    # <tag />
      xhtml  => $HTML,    # <tag />
      expand => $EXPAND,  # <tag></tag>
    );

  my %quote_style=
    ( double  => '"',
      single  => "'",
      # smart  => "smart",
    );

  my $xml_space_preserve; # set when an element includes xml:space="preserve"

  my $output_filter;      # filters the entire output (including < and >)
  my $output_text_filter; # filters only the text part (tag names, attributes, pcdata)

  my $replaced_ents= $REPLACED_ENTS;

  # returns those pesky "global" variables so you can switch between twigs
  sub global_state ## no critic (Subroutines::ProhibitNestedSubs);
    { return
       { pretty                    => $pretty,
         quote                     => $quote,
         indent                    => $INDENT,
         empty_tag_style           => $empty_tag_style,
         remove_cdata              => $remove_cdata,
         keep_encoding             => $keep_encoding,
         expand_external_entities  => $expand_external_entities,
         output_filter             => $output_filter,
         output_text_filter        => $output_text_filter,
         keep_atts_order           => $keep_atts_order,
         do_not_escape_amp_in_atts => $do_not_escape_amp_in_atts,
         wrap                      => $WRAP,
         replaced_ents             => $replaced_ents,
        };
    }

  # restores the global variables
  sub set_global_state
    { my $state= shift;
      $pretty                    = $state->{pretty};
      $quote                     = $state->{quote};
      $INDENT                    = $state->{indent};
      $empty_tag_style           = $state->{empty_tag_style};
      $remove_cdata              = $state->{remove_cdata};
      $keep_encoding             = $state->{keep_encoding};
      $expand_external_entities  = $state->{expand_external_entities};
      $output_filter             = $state->{output_filter};
      $output_text_filter        = $state->{output_text_filter};
      $keep_atts_order           = $state->{keep_atts_order};
      $do_not_escape_amp_in_atts = $state->{do_not_escape_amp_in_atts};
      $WRAP                      = $state->{wrap};
      $replaced_ents             = $state->{replaced_ents},
    }

  # sets global state to defaults
  sub init_global_state
    { set_global_state(
       { pretty                    => 0,
         quote                     => '"',
         indent                    => $INDENT,
         empty_tag_style           => 0,
         remove_cdata              => 0,
         keep_encoding             => 0,
         expand_external_entities  => 0,
         output_filter             => undef,
         output_text_filter        => undef,
         keep_atts_order           => undef,
         do_not_escape_amp_in_atts => 0,
         wrap                      => $WRAP,
         replaced_ents             => $REPLACED_ENTS,
        });
    }

  # set the pretty_print style (in $pretty) and returns the old one
  # can be called from outside the package with 2 arguments (elt, style)
  # or from inside with only one argument (style)
  # the style can be either a string (one of the keys of %pretty_print_style
  # or a number (presumably an old value saved)
  sub set_pretty_print
    { my $style= lc( defined $_[1] ? $_[1] : $_[0]); # so we cover both cases
      my $old_pretty= $pretty;
      if( $style=~ /^\d+$/)
        { croak "invalid pretty print style $style" unless( $style < keys %pretty_print_style);
          $pretty= $style;
        }
      else
        { croak "invalid pretty print style '$style'" unless( exists $pretty_print_style{$style});
          $pretty= $pretty_print_style{$style};
        }
      if( $WRAPPED{$pretty} )
        { XML::Twig::_use( 'Text::Wrap') or croak( "Text::Wrap not available, cannot use style $style"); }
      return $old_pretty;
    }

  sub _pretty_print { return $pretty; }

  # set the empty tag style (in $empty_tag_style) and returns the old one
  # can be called from outside the package with 2 arguments (elt, style)
  # or from inside with only one argument (style)
  # the style can be either a string (one of the keys of %empty_tag_style
  # or a number (presumably an old value saved)
  sub set_empty_tag_style
    { my $style= lc( defined $_[1] ? $_[1] : $_[0]); # so we cover both cases
      my $old_style= $empty_tag_style;
      if( $style=~ /^\d+$/)
        { croak "invalid empty tag style $style"
        unless( $style < keys %empty_tag_style);
        $empty_tag_style= $style;
        }
      else
        { croak "invalid empty tag style '$style'"
            unless( exists $empty_tag_style{$style});
          $empty_tag_style= $empty_tag_style{$style};
        }
      return $old_style;
    }

  sub _pretty_print_styles
    { return (sort { $pretty_print_style{$a} <=> $pretty_print_style{$b} || $a cmp $b } keys %pretty_print_style); }

  sub set_quote
    { my $style= $_[1] || $_[0];
      my $old_quote= $quote;
      croak "invalid quote '$style'" unless( exists $quote_style{$style});
      $quote= $quote_style{$style};
      return $old_quote;
    }

  sub set_remove_cdata
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $remove_cdata;
      $remove_cdata= $new_value;
      return $old_value;
    }

  sub set_indent
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $INDENT;
      $INDENT= $new_value;
      return $old_value;
    }

  sub set_wrap
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $WRAP;
      $WRAP= $new_value;
      return $old_value;
    }

  sub set_keep_encoding
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $keep_encoding;
      $keep_encoding= $new_value;
      return $old_value;
   }

  sub set_replaced_ents
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $replaced_ents;
      $replaced_ents= $new_value;
      return $old_value;
   }

  sub do_not_escape_gt
    { my $old_value= $replaced_ents;
      $replaced_ents= q{&<}; # & needs to be first
      return $old_value;
    }

  sub escape_gt
    { my $old_value= $replaced_ents;
      $replaced_ents= qq{&<>}; # & needs to be first
      return $old_value;
    }

  sub _keep_encoding { return $keep_encoding; } # so I can use elsewhere in the module

  sub set_do_not_escape_amp_in_atts
    { my $new_value= defined $_[1] ? $_[1] : $_[0];
      my $old_value= $do_not_escape_amp_in_atts;
      $do_not_escape_amp_in_atts= $new_value;
      return $old_value;
   }

  sub output_filter      { return $output_filter; }
  sub output_text_filter { return $output_text_filter; }

  sub set_output_filter
    { my $new_value= defined $_[1] ? $_[1] : $_[0]; # can be called in object/non-object mode
      # if called in object mode with no argument, the filter is undefined
      if( isa( $new_value, 'XML::Twig::Elt') || isa( $new_value, 'XML::Twig')) { undef $new_value; }
      my $old_value= $output_filter;

lib/XML/Twig.pm  view on Meta::CPAN

  }

  # same as print but does not output the start tag if the element
  # is marked as flushed
  sub flush
    { my $elt= shift;
      my $up_to= $_[0] && isa( $_[0], 'XML::Twig::Elt') ? shift : $elt;
      $elt->twig->flush_up_to( $up_to, @_);
    }
  sub purge
    { my $elt= shift;
      my $up_to= $_[0] && isa( $_[0], 'XML::Twig::Elt') ? shift : $elt;
      $elt->twig->purge_up_to( $up_to, @_);
    }

  sub _flush
    { my $elt= shift;

      my $pretty;
      my $fh=  _is_fh( $_[0]) ? shift : undef;
      my $old_select= defined $fh ? select $fh : undef;
      my $old_pretty= defined ($pretty= shift) ? set_pretty_print( $pretty) : undef;

      $xml_space_preserve= 1 if( ($elt->inherit_att( 'xml:space') || '') eq 'preserve');

      $elt->__flush();

      $xml_space_preserve= 0;

      select $old_select if( defined $old_select);
      set_pretty_print( $old_pretty) if( defined $old_pretty);
    }

  sub __flush
    { my $elt= shift;

      if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
        { my $preserve= ($elt->att( 'xml:space') || '') eq 'preserve';
          $xml_space_preserve++ if $preserve;
          unless( $elt->_flushed)
            { print $elt->start_tag();
            }

          # flush the children
          my @children= $elt->_children;
          foreach my $child (@children)
            { $child->_flush( $pretty);
              $child->_set_flushed;
            }
          if( ! $elt->{end_tag_flushed})
            { print $elt->end_tag;
              $elt->{end_tag_flushed}=1;
              $elt->_set_flushed;
            }
          $xml_space_preserve-- if $preserve;
          # used for pretty printing
          if( my $parent= $elt->parent) { $parent->{has_flushed_child}= 1; }
        }
      else # text or special element
        { my $text;
          if( $elt->is_pcdata)     { $text= $elt->pcdata_xml_string;
                                     if( my $parent= $elt->parent)
                                       { $parent->{contains_text}= 1; }
                                   }
          elsif( $elt->is_cdata)   { $text= $elt->cdata_string;
                                     if( my $parent= $elt->parent)
                                       { $parent->{contains_text}= 1; }
                                   }
          elsif( $elt->is_pi)      { $text= $elt->pi_string;          }
          elsif( $elt->is_comment) { $text= $elt->comment_string;     }
          elsif( $elt->is_ent)     { $text= $elt->ent_string;         }

          print $output_filter ? $output_filter->( $text) : $text;
        }
    }

  sub xml_text
    { my( $elt, @options)= @_;

      if( @options && grep { lc( $_) eq 'no_recurse' } @options) { return $elt->xml_text_only; }

      my $string='';

      if( ($elt->{gi} >= $XML::Twig::SPECIAL_GI) )
        { # sprint the children
          my $child= $elt->_first_child || '';
          while( $child)
            { $string.= $child->xml_text;
            } continue { $child= $child->_next_sibling; }
        }
      elsif( $elt->is_pcdata)  { $string .= $output_filter ?  $output_filter->($elt->pcdata_xml_string)
                                                           : $elt->pcdata_xml_string;
                               }
      elsif( $elt->is_cdata)   { $string .= $output_filter ?  $output_filter->($elt->cdata_string)
                                                           : $elt->cdata_string;
                               }
      elsif( $elt->is_ent)     { $string .= $elt->ent_string; }

      return $string;
    }

  sub xml_text_only
    { return join '', map { $_->xml_text if( $_->is_text || $_->is_ent) } $_[0]->_children; }

  # same as print but except... it does not print but rather returns the string
  # if the second parameter is set then only the content is returned, not the
  # start and end tags of the element (but the tags of the included elements are
  # returned)

  sub sprint
    { my $elt= shift;
      my( $old_pretty, $old_empty_tag_style);

      if( $_[0])
        { if( isa( $_[0], 'HASH'))
            { # "proper way, using a hashref for options
              my %args= XML::Twig::_normalize_args( %{shift()});
              if( defined $args{PrettyPrint}) { $old_pretty          = set_pretty_print( $args{PrettyPrint});  }
              if( defined $args{EmptyTags})   { $old_empty_tag_style = set_empty_tag_style( $args{EmptyTags}); }
            }
          else
            { # "old" way, just using the option name
              my @other_opt;
              foreach my $opt (@_)
                { if( exists $pretty_print_style{$opt}) { $old_pretty = set_pretty_print( $opt);             }
                  elsif( exists $empty_tag_style{$opt}) { $old_empty_tag_style = set_empty_tag_style( $opt); }
                  else                                  { push @other_opt, $opt;                             }
                }
               @_= @other_opt;
            }
        }

      $xml_space_preserve= 1 if( ($elt->inherit_att( 'xml:space') || '') eq 'preserve');

      @sprint=();
      $elt->_sprint( @_);
      my $sprint= join( '', @sprint);
      if( $output_filter) { $sprint= $output_filter->( $sprint); }

      if( ( ($pretty== $WRAPPED) || ($pretty==$INDENTEDC)) && !$xml_space_preserve)
        { $sprint= _wrap_text( $sprint); }
      $xml_space_preserve= 0;

      if( defined $old_pretty)          { set_pretty_print( $old_pretty);             }
      if( defined $old_empty_tag_style) { set_empty_tag_style( $old_empty_tag_style); }

      return $sprint;
    }

  sub _wrap_text
    { my( $string)= @_;
      my $wrapped;
      foreach my $line (split /\n/, $string)
        { my( $initial_indent)= $line=~ m{^(\s*)};
          my $wrapped_line= Text::Wrap::wrap(  '',  $initial_indent . $INDENT, $line) . "\n";

          # fix glitch with Text::wrap when the first line is long and does not include spaces
          # the first line ends up being too short by 2 chars, but we'll have to live with it!
          $wrapped_line=~ s{^ +\n  }{}s; # this prefix needs to be removed

          $wrapped .= $wrapped_line;
        }
      return $wrapped;
    }

  sub _sprint
    { my $elt= shift;
      my $no_tag= shift || 0;
      # in case there's some comments or PI's piggybacking

      if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
        {
          my $preserve= ($elt->att( 'xml:space') || '') eq 'preserve';
          $xml_space_preserve++ if $preserve;

          push @sprint, $elt->start_tag unless( $no_tag);

          # sprint the children
          my $child= $elt->_first_child;
          while( $child)
            { $child->_sprint;
              $child= $child->_next_sibling;
            }
          push @sprint, $elt->end_tag unless( $no_tag);
          $xml_space_preserve-- if $preserve;
        }
      else
        { push @sprint, $elt->{extra_data} if( $elt->{extra_data}) ;
          if(    $elt->is_pcdata)  { push @sprint, $elt->pcdata_xml_string; }
          elsif( $elt->is_cdata)   { push @sprint, $elt->cdata_string;      }
          elsif( $elt->is_pi)      { if( ($pretty >= $INDENTED) && !$elt->parent->{contains_text}) { push @sprint, "\n" . $INDENT x $elt->level; }
                                     push @sprint, $elt->pi_string;
                                   }
          elsif( $elt->is_comment) { if( ($pretty >= $INDENTED) && !$elt->parent->{contains_text}) { push @sprint, "\n" . $INDENT x $elt->level; }
                                     push @sprint, $elt->comment_string;
                                   }
          elsif( $elt->is_ent)     { push @sprint, $elt->ent_string;        }
        }

      return;
    }

  # just a shortcut to $elt->sprint( 1)
  sub xml_string
    { my $elt= shift;
      isa( $_[0], 'HASH') ?  $elt->sprint( shift(), 1) : $elt->sprint( 1);
    }

  sub pcdata_xml_string
    { my $elt= shift;
      if( defined( my $string= $elt->{pcdata}) )
        {
          if( ! $elt->_extra_data_in_pcdata)
            {
              $string=~ s/([$replaced_ents])/$XML::Twig::base_ent{$1}/g unless( !$replaced_ents || $keep_encoding || $elt->{asis});
              $string=~ s{\Q]]>}{]]&gt;}g;
            }
          else
            { _gen_mark( $string); # used by _(un)?protect_extra_data
              foreach my $data (reverse @{$elt->_extra_data_in_pcdata})
                { my $substr= substr( $string, $data->{offset});
                  if( $keep_encoding || $elt->{asis})
                    { substr( $string, $data->{offset}, 0, $data->{text}); }
                  else
                    { substr( $string, $data->{offset}, 0, _protect_extra_data( $data->{text})); }
                }
              unless( $keep_encoding || $elt->{asis})
                {
                  $string=~ s{([$replaced_ents])}{$XML::Twig::base_ent{$1}}g ;
                  $string=~ s{\Q]]>}{]]&gt;}g;
                  _unprotect_extra_data( $string);
                }
            }
          return $output_text_filter ? $output_text_filter->( $string) : $string;
        }
      else
        { return ''; }
    }

  { my $mark;
    my( %char2ent, %ent2char);
    BEGIN
      { %char2ent= ( '<' => 'lt', '&' => 'amp', '>' => 'gt');
        %ent2char= map { $char2ent{$_} => $_ } keys %char2ent;
      }

    # generate a unique mark (a string) not found in the string,
    # used to mark < and & in the extra data
    sub _gen_mark
      { $mark="AAAA";
        $mark++ while( index( $_[0], $mark) > -1);
        return $mark;
      }

    sub _protect_extra_data
      { my( $extra_data)= @_;
        $extra_data=~ s{([<&>])}{:$mark:$char2ent{$1}:}g;
        return $extra_data;
      }

    sub _unprotect_extra_data
      { $_[0]=~ s{:$mark:(\w+):}{$ent2char{$1}}g; }

  }

  sub cdata_string
    { my $cdata= $_[0]->cdata;
      unless( defined $cdata) { return ''; }
      if( $remove_cdata)
        { $cdata=~ s/([$replaced_ents])/$XML::Twig::base_ent{$1}/g; }
      else
        { # if the CDATA includes the end of CDATA marker, we need to split it
          $cdata=~ s{$CDATA_END}{]]$CDATA_END$CDATA_START>}g;
          $cdata= $CDATA_START . $cdata . $CDATA_END;
        }
      return $cdata;
   }

  sub att_xml_string
    { my $elt= shift;
      my $att= shift;

      my $replace= $replaced_ents . "$quote\n\r\t";
      if($_[0] && $_[0]->{escape_gt} && ($replace!~ m{>}) ) { $replace .='>'; }

      if( defined (my $string= $elt->{att}->{$att}))
        { return _att_xml_string( $string, $replace); }
      else
        { return ''; }
    }

  # escaped xml string for an attribute value
  sub _att_xml_string
    { my( $string, $escape)= @_;
      if( !defined( $string)) { return ''; }
      if( $keep_encoding)
        { $string=~ s{$quote}{$XML::Twig::base_ent{$quote}}g;
        }
      else
        {
          if( $do_not_escape_amp_in_atts)
            { $escape=~ s{^.}{}; # seems like the most backward compatible way to remove & from the list
              $string=~ s{([$escape])}{$XML::Twig::base_ent{$1}}g;
              $string=~ s{&(?!(\w+|#\d+|[xX][0-9a-fA-F]+);)}{&amp;}g; # dodgy: escape & that do not start an entity
            }
          else
            { $string=~ s{([$escape])}{$XML::Twig::base_ent{$1}}g;
              $string=~ s{\Q]]>}{]]&gt;}g;
            }
        }

      return $output_text_filter ? $output_text_filter->( $string) : $string;
    }

  sub ent_string
    { my $ent= shift;
      my $ent_text= $ent->{ent};
      my( $t, $el, $ent_string);
      if(    $expand_external_entities
          && ($t= $ent->twig)
          && ($el= $t->entity_list)
          && ($ent_string= $el->{entities}->{$ent->ent_name}->{val})
        )
        { return $ent_string; }
       else
         { return $ent_text;  }
    }

  # returns just the text, no tags, for an element
  sub text
    { my( $elt, @options)= @_;

      if( @options && grep { lc( $_) eq 'no_recurse' } @options) { return $elt->text_only; }
      my $sep = (@options && grep { lc( $_) eq 'sep' } @options) ? ' ' : '';

      my $string;

      if( $elt->is_pcdata)     { return  $elt->pcdata    . $sep;  }
      elsif( $elt->is_cdata)   { return  $elt->cdata     . $sep;  }
      elsif( $elt->is_pi)      { return  $elt->pi_string . $sep;  }
      elsif( $elt->is_comment) { return  $elt->comment   . $sep;  }
      elsif( $elt->is_ent)     { return  $elt->ent       . $sep ; }

      my $child= $elt->_first_child ||'';
      while( $child)
        {
          my $child_text= $child->text( @options);
          $string.= defined( $child_text) ? $sep . $child_text : '';
        } continue { $child= $child->_next_sibling; }

      unless( defined $string) { $string=''; }

      return $output_text_filter ? $output_text_filter->( $string) : $string;
    }

  sub text_only
    { return join '', map { $_->text if( $_->is_text || $_->is_ent) } $_[0]->_children; }

  sub trimmed_text
    { my $elt= shift;
      my $text= $elt->text( @_);
      $text=~ s{\s+}{ }sg;
      $text=~ s{^\s}{};
      $text=~ s{\s$}{};
      return $text;
    }

  sub trim
    { my( $elt)= @_;
      my $pcdata= $elt->first_descendant( $TEXT);
      (my $pcdata_text= $pcdata->text)=~ s{^\s+}{}s;
      $pcdata->set_text( $pcdata_text);
      $pcdata= $elt->last_descendant( $TEXT);
      ($pcdata_text= $pcdata->text)=~ s{\s+$}{};
      $pcdata->set_text( $pcdata_text);
      foreach my $pcdata ($elt->descendants( $TEXT))
        { ($pcdata_text= $pcdata->text)=~ s{\s+}{ }g;
          $pcdata->set_text( $pcdata_text);
        }
      return $elt;
    }

  # remove cdata sections (turns them into regular pcdata) in an element
  sub remove_cdata
    { my $elt= shift;
      foreach my $cdata ($elt->descendants_or_self( $CDATA))
        { if( $keep_encoding)
            { my $data= $cdata->cdata;
              $data=~ s{([&<"'])}{$XML::Twig::base_ent{$1}}g;
              $cdata->set_pcdata( $data);
            }
          else
            { $cdata->set_pcdata( $cdata->cdata); }
          $cdata->set_gi( $PCDATA);
          undef $cdata->{cdata};
        }
    }

sub _is_private      { return _is_private_name( $_[0]->gi); }
sub _is_private_name { return $_[0]=~ m{^#(?!default:)};                }

} # end of block containing package globals ($pretty_print, $quotes, keep_encoding...)

# merges consecutive #PCDATAs in am element
sub normalize
  { my( $elt)= @_;
    my @descendants= $elt->descendants( $PCDATA);
    while( my $desc= shift @descendants)
      { if( ! length $desc->{pcdata}) { $desc->delete; next; }
        while( @descendants && $desc->_next_sibling && $desc->_next_sibling== $descendants[0])
          { my $to_merge= shift @descendants;
            $desc->merge_text( $to_merge);
          }
      }
    return $elt;
  }

# SAX export methods
sub toSAX1
  { _toSAX(@_, \&_start_tag_data_SAX1, \&_end_tag_data_SAX1); }

sub toSAX2
  { _toSAX(@_, \&_start_tag_data_SAX2, \&_end_tag_data_SAX2); }

sub _toSAX
  { my( $elt, $handler, $start_tag_data, $end_tag_data)= @_;
    if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
      { my $data= $start_tag_data->( $elt);
        _start_prefix_mapping( $elt, $handler, $data);
        if( $data && (my $start_element = $handler->can( 'start_element')))
          { unless( $elt->_flushed) { $start_element->( $handler, $data); } }

        foreach my $child ($elt->_children)
          { $child->_toSAX( $handler, $start_tag_data, $end_tag_data); }

        if( (my $data= $end_tag_data->( $elt)) && (my $end_element = $handler->can( 'end_element')) )
          { $end_element->( $handler, $data); }
        _end_prefix_mapping( $elt, $handler);
      }
    else # text or special element
      { if( $elt->is_pcdata && (my $characters= $handler->can( 'characters')))
          { $characters->( $handler, { Data => $elt->pcdata });  }
        elsif( $elt->is_cdata)
          { if( my $start_cdata= $handler->can( 'start_cdata'))
              { $start_cdata->( $handler); }
            if( my $characters= $handler->can( 'characters'))
              { $characters->( $handler, {Data => $elt->cdata });  }
            if( my $end_cdata= $handler->can( 'end_cdata'))
              { $end_cdata->( $handler); }
          }
        elsif( ($elt->is_pi)  && (my $pi= $handler->can( 'processing_instruction')))
          { $pi->( $handler, { Target =>$elt->target, Data => $elt->data });  }
        elsif( ($elt->is_comment)  && (my $comment= $handler->can( 'comment')))
          { $comment->( $handler, { Data => $elt->comment });  }
        elsif( ($elt->is_ent))
          {
            if( my $se=   $handler->can( 'skipped_entity'))
              { $se->( $handler, { Name => $elt->ent_name });  }
            elsif( my $characters= $handler->can( 'characters'))
              { if( defined $elt->ent_string)
                  { $characters->( $handler, {Data => $elt->ent_string});  }
                else
                  { $characters->( $handler, {Data => $elt->ent_name});  }
              }
          }

      }
  }

sub _start_tag_data_SAX1
  { my( $elt)= @_;
    my $name= $elt->gi;
    return if( $elt->_is_private);
    my $attributes={};
    my $atts= $elt->atts;
    while( my( $att, $value)= each %$atts)
      { $attributes->{$att}= $value unless( _is_private_name( $att)); }
    my $data= { Name => $name, Attributes => $attributes};
    return $data;
  }

sub _end_tag_data_SAX1
  { my( $elt)= @_;
    return if( $elt->_is_private);
    return  { Name => $elt->gi };
  }

sub _start_tag_data_SAX2
  { my( $elt)= @_;
    my $data={};

    my $name= $elt->gi;
    return if( $elt->_is_private);
    $data->{Name}         = $name;
    $data->{Prefix}       = $elt->ns_prefix;
    $data->{LocalName}    = $elt->local_name;
    $data->{NamespaceURI} = $elt->namespace;

    # save a copy of the data so we can re-use it for the end tag
    my %sax2_data= %$data;
    $elt->{twig_elt_SAX2_data}= \%sax2_data;

    # add the attributes
    $data->{Attributes}= $elt->_atts_to_SAX2;

    return $data;
  }

sub _atts_to_SAX2

lib/XML/Twig.pm  view on Meta::CPAN

    my $SAX2_atts= {};
    foreach my $att (keys %{$elt->atts})
      {
        next if( _is_private_name( $att));
        my $SAX2_att={};
        $SAX2_att->{Name}         = $att;
        $SAX2_att->{Prefix}       = _ns_prefix( $att);
        $SAX2_att->{LocalName}    = _local_name( $att);
        $SAX2_att->{NamespaceURI} = $elt->namespace( $SAX2_att->{Prefix});
        $SAX2_att->{Value}        = $elt->att( $att);
        my $SAX2_att_name= "{$SAX2_att->{NamespaceURI}}$SAX2_att->{LocalName}";

        $SAX2_atts->{$SAX2_att_name}= $SAX2_att;
      }
    return $SAX2_atts;
  }

sub _start_prefix_mapping
  { my( $elt, $handler, $data)= @_;
    if( my $start_prefix_mapping= $handler->can( 'start_prefix_mapping')
        and my @new_prefix_mappings= grep { /^\{[^}]*\}xmlns/ || /^\{$XMLNS_URI\}/ } keys %{$data->{Attributes}}
      )
      { foreach my $prefix (@new_prefix_mappings)
          { my $prefix_string= $data->{Attributes}->{$prefix}->{LocalName};
            if( $prefix_string eq 'xmlns') { $prefix_string=''; }
            my $prefix_data=
              {  Prefix       => $prefix_string,
                 NamespaceURI => $data->{Attributes}->{$prefix}->{Value}
              };
            $start_prefix_mapping->( $handler, $prefix_data);
            $elt->{twig_end_prefix_mapping} ||= [];
            push @{$elt->{twig_end_prefix_mapping}}, $prefix_string;
          }
      }
  }

sub _end_prefix_mapping
  { my( $elt, $handler)= @_;
    if( my $end_prefix_mapping= $handler->can( 'end_prefix_mapping'))
      { foreach my $prefix (@{$elt->{twig_end_prefix_mapping}})
          { $end_prefix_mapping->( $handler, { Prefix => $prefix} ); }
      }
  }

sub _end_tag_data_SAX2
  { my( $elt)= @_;
    return if( $elt->_is_private);
    return $elt->{twig_elt_SAX2_data};
  }

sub contains_text
  { my $elt= shift;
    my $child= $elt->_first_child;
    while ($child)
      { return 1 if( $child->is_text || $child->is_ent);
        $child= $child->_next_sibling;
      }
    return 0;
  }

# creates a single pcdata element containing the text as child of the element
# options:
#   - force_pcdata: when set to a true value forces the text to be in a #PCDATA
#                   even if the original element was a #CDATA
sub set_text
  { my( $elt, $string, %option)= @_;

    if( $elt->gi eq $PCDATA)
      { return $elt->set_pcdata( $string); }
    elsif( $elt->gi eq $CDATA)
      { if( $option{force_pcdata})
          { $elt->set_gi( $PCDATA);
            $elt->_set_cdata('');
            return $elt->set_pcdata( $string);
          }
        else
          { $elt->_set_cdata( $string);
            return $string;
          }
      }
    elsif( $elt->contains_a_single( $PCDATA) )
      { # optimized so we have a slight chance of not losing embedded comments and pi's
        $elt->_first_child->set_pcdata( $string);
        return $elt;
      }

    foreach my $child (@{[$elt->_children]})
      { $child->delete; }

    my $pcdata= $elt->_new_pcdata( $string);
    $pcdata->paste( $elt);

    $elt->set_not_empty;

    return $elt;
  }

# set the content of an element from a list of strings and elements
sub set_content
  { my $elt= shift;

    return $elt unless defined $_[0];

    # attributes can be given as a hash (passed by ref)
    if( ref $_[0] eq 'HASH')
      { my $atts= shift;
        $elt->del_atts; # usually useless but better safe than sorry
        $elt->set_atts( $atts);
        return $elt unless defined $_[0];
      }

    # check next argument for #EMPTY
    if( !(ref $_[0]) && ($_[0] eq $EMPTY) )
      { $elt->set_empty; return $elt; }

    # case where we really want to do a set_text, the element is '#PCDATA'
    # or contains a single PCDATA and we only want to add text in it
    if( ($elt->gi eq $PCDATA || $elt->contains_a_single( $PCDATA))
        && (@_ == 1) && !( ref $_[0]))
      { $elt->set_text( $_[0]);
        return $elt;
      }
    elsif( ($elt->gi eq $CDATA) && (@_ == 1) && !( ref $_[0]))
      { $elt->_set_cdata( $_[0]);
        return $elt;
      }

    # delete the children
    foreach my $child (@{[$elt->_children]})
      { $child->delete; }

    if( @_) { $elt->set_not_empty; }

    foreach my $child (@_)
      { if( ref( $child) && isa( $child, 'XML::Twig::Elt'))
          { # argument is an element
            $child->paste( 'last_child', $elt);
          }
        else
          { # argument is a string
            if( (my $pcdata= $elt->_last_child) && $elt->_last_child->is_pcdata)
              { # previous child is also pcdata: just concatenate
                $pcdata->set_pcdata( $pcdata->pcdata . $child)
              }
            else
              { # previous child is not a string: create a new pcdata element
                $pcdata= $elt->_new_pcdata( $child);
                $pcdata->paste( 'last_child', $elt);
              }
          }
      }

    return $elt;
  }

# inserts an element (whose gi is given) as child of the element
# all children of the element are now children of the new element
# returns the new element
sub insert
  { my ($elt, @args)= @_;
    # first cut the children
    my @children= $elt->_children;
    foreach my $child (@children)
      { $child->cut; }
    # insert elements
    while( my $gi= shift @args)
      { my $new_elt= $elt->new( $gi);
        # add attributes if needed
        if( defined( $args[0]) && ( isa( $args[0], 'HASH')) )
          { $new_elt->set_atts( shift @args); }
        # paste the element
        $new_elt->paste( $elt);
        $elt->set_not_empty;
        $elt= $new_elt;
      }
    # paste back the children
    foreach my $child (@children)
      { $child->paste( 'last_child', $elt); }
    return $elt;
  }

# insert a new element
# $elt->insert_new_element( $opt_position, $gi, $opt_atts_hash, @opt_content);
# the element is created with the same syntax as new
# position is the same as in paste, first_child by default
sub insert_new_elt {
    my $elt= shift;
    my $position= _op_position($_[0]);
    if( $OP_POSITION{$position} )
      { shift; }
    else
      { $position= 'first_child'; }

    my $new_elt =  !ref( $_[0] ) && $_[0] =~ m{^\s*<}
        ? $elt->parse( $_[0], elt_class => ref($elt) ) # arg is an xml string
        : $elt->new( @_);                              # args are tag/atts/conten

    $new_elt->paste( $position, $elt);
}

# wraps an element in elements which gi's are given as arguments
# $elt->wrap_in( 'td', 'tr', 'table') wraps the element as a single
# cell in a table for example
# returns the new element
sub wrap_in
  { my $elt= shift;
    my $t= $elt->twig;
    while( my $gi = shift @_)

lib/XML/Twig.pm  view on Meta::CPAN


        $elt->set_parent( $new_elt);
        $elt->set_prev_sibling( undef);
        $elt->set_next_sibling( undef);

        # add the attributes if the next argument is a hash ref
        if( defined( $_[0]) && (isa( $_[0], 'HASH')) )
          { $new_elt->set_atts( shift @_); }

        $elt= $new_elt;
      }

    return $elt;
  }

sub replace
  { my( $elt, $ref)= @_;

    if( $elt->_parent) { $elt->cut; }

    if( my $parent= $ref->_parent)
      { $elt->set_parent( $parent);
        if( $parent->_first_child == $ref) { $parent->set_first_child( $elt); }
        if( $parent->_last_child == $ref)  { $parent->set_last_child( $elt) ; }
      }
    elsif( $ref->twig && $ref == $ref->twig->root)
      { $ref->twig->set_root( $elt); }

    if( my $prev_sibling= $ref->_prev_sibling)
      { $elt->set_prev_sibling( $prev_sibling);
        $prev_sibling->set_next_sibling( $elt);
      }
    if( my $next_sibling= $ref->_next_sibling)
      { $elt->set_next_sibling( $next_sibling);
        $next_sibling->set_prev_sibling( $elt);
      }

    $ref->set_parent( undef);
    $ref->set_prev_sibling( undef);
    $ref->set_next_sibling( undef);
    return $ref;
  }

sub replace_with
  { my $ref= shift;
    my $elt= shift;
    $elt->replace( $ref);
    foreach my $new_elt (reverse @_)
      { $new_elt->paste( after => $elt); }
    return $elt;
  }

# move an element, same syntax as paste, except the element is first cut
sub move
  { my $elt= shift;
    $elt->cut;
    $elt->paste( @_);
    return $elt;
  }

# adds a prefix to an element, creating a pcdata child if needed
sub prefix
  { my ($elt, $prefix, $option)= @_;
    my $asis= ($option && ($option eq 'asis')) ? 1 : 0;
    if( $elt->is_pcdata
        && (($asis && $elt->{asis}) || (!$asis && ! $elt->{asis}))
      )
      { $elt->set_pcdata( $prefix . $elt->pcdata); }
    elsif( $elt->_first_child && $elt->_first_child->is_pcdata
        && (   ($asis && $elt->_first_child->{asis})
            || (!$asis && ! $elt->_first_child->{asis}))
         )
      {
        $elt->_first_child->set_pcdata( $prefix . $elt->_first_child->pcdata);
      }
    else
      { my $new_elt= $elt->_new_pcdata( $prefix);
        my $pos= $elt->is_pcdata ? 'before' : 'first_child';
        $new_elt->paste( $pos => $elt);
        if( $asis) { $new_elt->set_asis; }
      }
    return $elt;
  }

# adds a suffix to an element, creating a pcdata child if needed
sub suffix
  { my ($elt, $suffix, $option)= @_;
    my $asis= ($option && ($option eq 'asis')) ? 1 : 0;
    if( $elt->is_pcdata
        && (($asis && $elt->{asis}) || (!$asis && ! $elt->{asis}))
      )
      { $elt->set_pcdata( $elt->pcdata . $suffix); }
    elsif( $elt->_last_child && $elt->_last_child->is_pcdata
        && (   ($asis && $elt->_last_child->{asis})
            || (!$asis && ! $elt->_last_child->{asis}))
         )
      { $elt->_last_child->set_pcdata( $elt->_last_child->pcdata . $suffix); }
    else
      { my $new_elt= $elt->_new_pcdata( $suffix);
        my $pos= $elt->is_pcdata ? 'after' : 'last_child';
        $new_elt->paste( $pos => $elt);
        if( $asis) { $new_elt->set_asis; }
      }
    return $elt;
  }

# create a path to an element ('/root/.../gi)
sub path
  { my $elt= shift;
    my @context= ( $elt, $elt->ancestors);
    return "/" . join( "/", reverse map {$_->gi} @context);
  }

sub xpath
  { my $elt= shift;
    my $xpath;
    foreach my $ancestor (reverse $elt->ancestors_or_self)
      { my $gi= $ancestor->gi;
        $xpath.= "/$gi";
        my $index= $ancestor->prev_siblings( $gi) + 1;
        unless( ($index == 1) && !$ancestor->next_sibling( $gi))
          { $xpath.= "[$index]"; }
      }
    return $xpath;
  }

# methods used mainly by wrap_children

# return a string with the
# for an element <foo><elt att="val">...</elt><elt2/><elt>...</elt></foo>
# returns '<elt att="val"><elt2><elt>'
sub _stringify_struct
  { my( $elt, %opt)= @_;
    my $string='';
    my $pretty_print= set_pretty_print( 'none');
    foreach my $child ($elt->_children)
      { $child->add_id; $string .= $child->start_tag( { escape_gt => 1 }) ||''; }
    set_pretty_print( $pretty_print);
    return $string;
  }

# wrap a series of elements in a new one
sub _wrap_range
  { my $elt= shift;
    my $gi= shift;
    my $atts= isa( $_[0], 'HASH') ? shift : undef;
    my $range= shift; # the string with the tags to wrap

    my $t= $elt->twig;

    # get the tags to wrap
    my @to_wrap;
    while( $range=~ m{<[\w.*-]+\s+[^>]*id=("[^"]*"|'[^']*')[^>]*>}g)
      { push @to_wrap, $t->elt_id( substr( $1, 1, -1)); }

    return '' unless @to_wrap;

    my $to_wrap= shift @to_wrap;
    my %atts= %$atts;
    my $new_elt= $to_wrap->wrap_in( $gi, \%atts);

lib/XML/Twig.pm  view on Meta::CPAN

    return -1 if( $b->in($a)); # b in a => a starts before b

    # ancestors does not include the element itself
    my @a_pile= ($a, $a->ancestors);
    my @b_pile= ($b, $b->ancestors);

    # the 2 elements are not in the same twig
    return undef unless( $a_pile[-1] == $b_pile[-1]);

    # find the first non common ancestors (they are siblings)
    my $a_anc= pop @a_pile;
    my $b_anc= pop @b_pile;

    while( $a_anc == $b_anc)
      { $a_anc= pop @a_pile;
        $b_anc= pop @b_pile;
      }

    # from there move left and right and figure out the order
    my( $a_prev, $a_next, $b_prev, $b_next)= ($a_anc, $a_anc, $b_anc, $b_anc);
    while()
      { $a_prev= $a_prev->_prev_sibling || return( -1);
        return 1 if( $a_prev == $b_next);
        $a_next= $a_next->_next_sibling || return( 1);
        return -1 if( $a_next == $b_prev);
        $b_prev= $b_prev->_prev_sibling || return( 1);
        return -1 if( $b_prev == $a_next);
        $b_next= $b_next->_next_sibling || return( -1);
        return 1 if( $b_next == $a_prev);
      }
  }

sub _dump
  { my( $elt, $option)= @_;

    my $atts       = defined $option->{atts}       ? $option->{atts}       :  1;
    my $extra      = defined $option->{extra}      ? $option->{extra}      :  0;
    my $short_text = defined $option->{short_text} ? $option->{short_text} : 40;
    # $option->{depth} is the number of levels that should be dumped

    my $sp= '| ';
    my $indent= $sp x $elt->level;
    my $indent_sp= '  ' x $elt->level;

    my $dump='';
    if( $elt->is_elt)
      {
        $dump .= $indent  . '|-' . $elt->gi;

        if( $atts && (my @atts= $elt->att_names) )
          { $dump .= ' ' . join( ' ', map { qq{$_="} . $elt->att( $_) . qq{"} } @atts); }

        $dump .= "\n";
        if( $extra) { $dump .= $elt->_dump_extra_data( $indent, $indent_sp, $short_text); }

        if( exists $option->{depth}) { $option->{depth}--; }
        $dump .= join( "", map { $_->_dump( $option) } $elt->_children) unless exists $option->{depth} && $option->{depth} <= 0;
      }
    else
      {
        if( $elt->is_pcdata)
          { $dump .= "$indent|-PCDATA:  '"  . _short_text( $elt->pcdata, $short_text) . "'\n" }
        elsif( $elt->is_ent)
          { $dump .= "$indent|-ENTITY:  '" . _short_text( $elt->ent, $short_text) . "'\n" }
        elsif( $elt->is_cdata)
          { $dump .= "$indent|-CDATA:   '" . _short_text( $elt->cdata, $short_text) . "'\n" }
        elsif( $elt->is_comment)
          { $dump .= "$indent|-COMMENT: '" . _short_text( $elt->comment_string, $short_text) . "'\n" }
        elsif( $elt->is_pi)
          { $dump .= "$indent|-PI:      '"      . $elt->target . "' - '" . _short_text( $elt->data, $short_text) . "'\n" }
        if( $extra) { $dump .= $elt->_dump_extra_data( $indent, $indent_sp, $short_text); }
      }
    return $dump;
  }

sub _dump_extra_data
  { my( $elt, $indent, $indent_sp, $short_text)= @_;
    my $dump='';
    if( $elt->extra_data)
      { my $extra_data = $indent . "|-- (cpi before) '" . _short_text( $elt->extra_data, $short_text) . "'";
        $extra_data=~ s{\n}{$indent_sp}g;
        $dump .= $extra_data . "\n";
      }
    if( $elt->_extra_data_in_pcdata)
      { foreach my $data ( @{$elt->_extra_data_in_pcdata})
          { my $extra_data = $indent . "|-- (cpi offset $data->{offset}) '" . _short_text( $data->{text}, $short_text) . "'";
            $extra_data=~ s{\n}{$indent_sp}g;
            $dump .= $extra_data . "\n";
          }
      }
    if( $elt->_extra_data_before_end_tag)
      { my $extra_data = $indent . "|-- (cpi end) '" . _short_text( $elt->_extra_data_before_end_tag, $short_text) . "'";
        $extra_data=~ s{\n}{$indent_sp}g;
        $dump .= $extra_data . "\n";
      }
    return $dump;
  }

sub _short_text
  { my( $string, $length)= @_;
    if( !$length || (length( $string) < $length) ) { return $string; }
    my $l1= (length( $string) -5) /2;
    my $l2= length( $string) - ($l1 + 5);
    return substr( $string, 0, $l1) . ' ... ' . substr( $string, -$l2);
  }

sub _and { return _join_defined( ' && ',  map { $_ } @_); }
sub _join_defined { return join( shift(), grep { $_ } @_); }

1;
__END__
=head1 NAME

XML::Twig - A perl module for processing huge XML documents in tree mode.

=head1 SYNOPSIS

Note that this documentation is intended as a reference to the module.

Complete docs, including a tutorial, examples, an easier to use HTML version,
a quick reference card and a FAQ are available at L<http://www.xmltwig.org/xmltwig>.

Small documents (loaded in memory as a tree):

  my $twig=XML::Twig->new();    # create the twig
  $twig->parsefile( 'doc.xml'); # build it
  my_process( $twig);           # use twig methods to process it
  $twig->print;                 # output the twig

Huge documents (processed in combined stream/tree mode):

  # at most one div will be loaded in memory
  my $twig=XML::Twig->new(
    twig_handlers =>
      { title   => sub { $_->set_tag( 'h2') }, # change title tags to h2
                                               # $_ is the current element
        para    => sub { $_->set_tag( 'p')  }, # change para to p
        hidden  => sub { $_->delete;       },  # remove hidden elements
        list    => \&my_list_process,          # process list elements
        div     => sub { $_[0]->flush;     },  # output and free memory
      },
    pretty_print => 'indented',                # output will be nicely formatted
    empty_tags   => 'html',                    # outputs <empty_tag />
                         );
  $twig->parsefile( 'my_big.xml');

lib/XML/Twig.pm  view on Meta::CPAN

=item iconv_convert ($encoding)

This function is used to create a filter subroutine that will be used to
convert the characters to the target encoding using C<Text::Iconv> (which needs
to be installed, see the documentation for the module and for the
C<iconv> library to find out which encodings are available on your system).

   my $conv = XML::Twig::iconv_convert( 'latin1');
   my $t = XML::Twig->new(output_filter => $conv);

=item unicode_convert ($encoding)

This function is used to create a filter subroutine that will be used to
convert the characters to the target encoding using C<Unicode::Strings>
and C<Unicode::Map8> (which need to be installed, see the documentation
for the modules to find out which encodings are available on your system).

   my $conv = XML::Twig::unicode_convert( 'latin1');
   my $t = XML::Twig->new(output_filter => $conv);

=back

The C<text> and C<att> methods do not use the filter, so their
result are always in unicode.

Those predeclared filters are based on subroutines that can be used
by themselves (as C<XML::Twig::foo>).

=over 4

=item html_encode ($string)

Use C<HTML::Entities> to encode a utf8 string.

=item safe_encode ($string)

Use C<Encode> to encode non-ascii characters in the string in C<< &#<nnnn>; >> format.

=item safe_encode_hex ($string)

Use C<Encode> to encode non-ascii characters in the string in C<< &#x<nnnn>; >> format.

=item regexp2latin1 ($string)

Use a regexp to encode a utf8 string into latin 1 (ISO-8859-1).

=back

=item output_text_filter

Same as output_filter, except it doesn't apply to the brackets and quotes
around attribute values. This is useful for all filters that could change
the tagging, basically anything that does not just change the encoding of
the output. C<html>, C<safe> and C<safe_hex> are better used with this option.

=item input_filter

This option is similar to C<output_filter> except the filter is applied to
the characters before they are stored in the twig, at parsing time.

=item remove_cdata

Setting this option to a true value will force the twig to output C<#CDATA>
sections as regular (escaped) C<#PCDATA>.

=item parse_start_tag

If you use the C<keep_encoding> option, then this option can be used to replace
the default parsing function. You should provide a coderef (a reference to a
subroutine) as the argument. This subroutine takes the original tag (given
by XML::Parser::Expat C<original_string()> method) and returns a tag and the
attributes in a hash (or in a list attribute_name/attribute value).

=item no_xxe

Prevents external entities to be parsed.

This is a security feature, in case the input XML cannot be trusted. With this
option set to a true value defining external entities in the document will cause
the parse to fail.

This prevents an entity like C<< <!ENTITY xxe PUBLIC "bar" "/etc/passwd"> >> to
make the password field available in the document.

=item expand_external_ents

When this option is used, external entities (that are defined) are expanded
when the document is output using "print" functions such as C<L<print> >,
C<L<sprint> >, C<L<flush> > and C<L<xml_string> >.
Note that in the twig the entity will be stored as an element with a
'C<#ENT>' tag, the entity will not be expanded there, so you might want to
process the entities before outputting it.

If an external entity is not available, then the parse will fail.

A special case is when the value of this option is -1. In that case a missing
entity will not cause the parser to die, but its C<name>, C<sysid> and C<pubid>
will be stored in the twig as C<< $twig->{twig_missing_system_entities} >>
(a reference to an array of hashes { name => <name>, sysid => <sysid>,
pubid => <pubid> }). Yes, this is a bit of a hack, but it's useful in some
cases.

=item load_DTD

If this argument is set to a true value, C<parse> or C<parsefile> on the twig
will load the DTD information. This information can then be accessed through
the twig, in a C<DTD_handler> for example. This will load even an external DTD.

Default and fixed values for attributes will also be filled, based on the DTD.

Note that to do this the module will generate a temporary file in the current
directory. If this is a problem, let me know and I will add an option to
specify an alternate directory.

See L<DTD Handling> for more information.

=item DTD_handler

Sets a handler that will be called once the doctype (and the DTD) have been
loaded, with two arguments: the twig and the DTD.

lib/XML/Twig.pm  view on Meta::CPAN


=item discard_spaces_in

This argument sets C<keep_spaces> to true, but causes the twig builder to
discard spaces in the elements listed.

The syntax for using this argument is:

  XML::Twig->new( discard_spaces_in => [ 'elt1', 'elt2']);

=item keep_spaces_in

This argument sets C<discard_spaces> to true, but causes the twig builder to
keep spaces in the elements listed.

The syntax for using this argument is:

  XML::Twig->new( keep_spaces_in => [ 'elt1', 'elt2']);

B<Warning>: Adding this option can result in changes in the twig generated:
space that was previously discarded might end up in a new text element.

=item pretty_print

Sets the pretty print method. Values are 'C<none>' (default), 'C<nsgmls>',
'C<nice>', 'C<indented>', 'C<indented_c>', 'C<indented_a>',
'C<indented_close_tag>', 'C<cvs>', 'C<wrapped>', 'C<record>' and 'C<record_c>'.

pretty_print formats:

=over 4

=item none

The document is output as one ling string, with no line breaks except those
found within text elements.

=item nsgmls

Line breaks are inserted in safe places: that is within tags, between a tag
and an attribute, between attributes and before the > at the end of a tag.

This is quite ugly but better than C<none>, and it is very safe, the document
will still be valid (conforming to its DTD).

This is how the SGML parser C<sgmls> splits documents, hence the name.

=item nice

This option inserts line breaks before any tag that does not contain text (so
elements with textual content are not broken as the \n is the significant).

B<WARNING>: This option leaves the document well-formed but might make it
invalid (not conformant to its DTD). If you have elements declared as:

  <!ELEMENT foo (#PCDATA|bar)>

then a C<foo> element including a C<bar> one will be printed as:

  <foo>
  <bar>bar is just pcdata</bar>
  </foo>

This is invalid, as the parser will take the line break after the C<foo> tag
as a sign that the element contains PCDATA, it will then die when it finds the
C<bar> tag. This may or may not be important for you, but be aware of it!

=item indented

Same as C<nice> (and with the same warning) but indents elements according to
their level.

=item indented_c

Same as C<indented>, but a little more compact: the closing tags are on the
same line as the preceding text.

=item indented_close_tag

Same as C<indented>, except that the closing tag is also indented, to line up
with the tags within the element.

=item indented_a

This formats XML files in a line-oriented version control friendly way.
The format is described in L<http://tinyurl.com/2kwscq> (that's an Oracle
document with an insanely long URL).

Note that to be totaly conformant to the "spec", the order of attributes
should not be changed, so if they are not already in alphabetical order
you will need to use the C<L<keep_atts_order> > option.

=item cvs

Same as C<L<indented_a> >.

=item wrapped

Same as C<indented_c>, but lines are wrapped using L<Text::Wrap::wrap>. The
default length for lines is the default for C<$Text::Wrap::columns>, and can
be changed by changing that variable.

=item record

This is a record-oriented pretty print that display data in records, one field
per line (which looks a LOT like C<indented>).

=item record_c

Stands for record compact, one record per line.

=back

=item empty_tags

Sets the empty tag display style ('C<normal>', 'C<html>' or 'C<expand>').

C<normal> outputs an empty tag 'C<< <tag/> >>', C<html> adds a space
'C<< <tag /> >>' for elements that can be empty in XHTML and C<expand> outputs
'C<< <tag></tag> >>'.

=item quote

Sets the quote character for attributes ('C<single>' or 'C<double>').

=item escape_gt

By default XML::Twig does not escape the > character in its output, as it is not
mandated by the XML spec. With this option on, > is replaced by C<&gt;>.

=item comments

Sets the way comments are processed: 'C<drop>' (default), 'C<keep>' or
'C<process>'.

Comment processing options:

=over 4

=item drop

Drops the comments; they are not read, nor printed to the output.

=item keep

Comments are loaded and will appear on the output; they are not
accessible within the twig and will not interfere with processing
though.

B<Note>: Comments in the middle of a text element such as:

  <p>text <!-- comment --> more text --></p>

are kept at their original position in the text. Using "print"
methods like C<print> or C<sprint> will return the comments in the
text. Using C<text> or C<field> on the other hand will not.

Any use of C<set_pcdata> on the C<#PCDATA> element (directly or
through other methods like C<set_content>) will delete the comment(s).

=item process

Comments are loaded in the twig and are treated as regular elements
with a C<tag> value of C<#COMMENT>. This can interfere with processing if you
expect C<< $elt->{first_child} >> to be an element but find a comment there.
Schema validation will not protect you from this as comments can happen anywhere.
You can use C<< $elt->first_child( 'tag') >> (which is a good habit anyway)
to get what you want.

Consider using C<process> if you are outputting SAX events from XML::Twig.

=back

=item pi

Sets the way processing instructions are processed: 'C<drop>', 'C<keep>'
(default), or 'C<process>'.

Note that you can also set PI handlers in the C<twig_handlers> option:

  '?'       => \&handler
  '?target' => \&handler2

The handlers will be called with two parameters, the twig and the PI element if
C<pi> is set to C<process>, and with three, the twig, the target and the data if
C<pi> is set to C<keep>. Of course they will not be called if C<pi> is set to
C<drop>.

If C<pi> is set to C<keep>, the handler should return a string that will be used
as-is as the PI text (it should look like "C< <?target data?> >" or '' if you
want to remove the PI),

Only one handler will be called, C<?target> or C<?> if no specific handler for
that target is available.

=item map_xmlns

This option is passed a hashref that maps uris to prefixes. The prefixes in
the document will be replaced by the ones in the map. The mapped prefixes can
(actually have to) be used to trigger handlers, or navigate or query the document.

Example:

  my $t= XML::Twig->new( map_xmlns => {'http://www.w3.org/2000/svg' => "svg"},
                         twig_handlers =>
                           { 'svg:circle' => sub { $_->set_att( r => 20) } },
                         pretty_print => 'indented',
                       )
                  ->parse( '<doc xmlns:gr="http://www.w3.org/2000/svg">
                              <gr:circle cx="10" cy="90" r="10"/>
                           </doc>'
                         )
                  ->print;

This will output:

  <doc xmlns:svg="http://www.w3.org/2000/svg">
     <svg:circle cx="10" cy="90" r="20"/>

lib/XML/Twig.pm  view on Meta::CPAN


Options: see C<flush>.

=item trim

Trims the document: gets rid of initial and trailing spaces, and replaces multiple spaces
by a single one.

=item toSAX1 ($handler)

Sends SAX events for the twig to the SAX1 handler C<$handler>.

=item toSAX2 ($handler)

Sends SAX events for the twig to the SAX2 handler C<$handler>.

=item flush_toSAX1 ($handler)

Same as C<flush>, except that SAX events are sent to the SAX1 handler
C<$handler> instead of the twig being printed.

=item flush_toSAX2 ($handler)

Same as C<flush>, except that SAX events are sent to the SAX2 handler
C<$handler> instead of the twig being printed.

=item ignore

This method should be called during parsing, usually in C<start_tag_handlers>.
It causes the element to be skipped during the parsing: the twig is not built
for this element; it will not be accessible during parsing or after it. The
element does not take up any memory and parsing will be faster.

Note that this method can also be called on an element. If the element is a
parent of the current element then this element will be ignored (the twig will
not be built anymore for it and what has already been built will be deleted).

=item set_pretty_print ($style)

Set the pretty print method, amongst 'C<none>' (default), 'C<nsgmls>',
'C<nice>', 'C<indented>', C<indented_c>, 'C<wrapped>', 'C<record>' and
'C<record_c>'.

B<WARNING:> The pretty print style is a B<GLOBAL> variable, so once set it
applies to B<ALL> C<print>'s (and C<sprint>'s). Same goes if you use XML::Twig
with C<mod_perl>. This should not be a problem as the XML that's generated
is valid anyway, and XML processors (as well as HTML processors, including
browsers) should not care. Let me know if this is a big problem, but at the
moment the performance/cleanliness trade-off clearly favors the global
approach.

=item set_empty_tag_style ($style)

Sets the empty tag display style ('C<normal>', 'C<html>' or 'C<expand>'). As
with C<L<set_pretty_print> >, this sets a global flag.

C<normal> outputs an empty tag 'C<< <tag/> >>', C<html> adds a space
'C<< <tag /> >>' for elements that can be empty in XHTML, and C<expand> outputs
'C<< <tag></tag> >>'.

=item set_remove_cdata ($flag)

Sets (or unsets) the flag that forces the twig to output C<#CDATA> sections as
regular (escaped) C<#PCDATA>.

=item print_prolog ($optional_filehandle, %options)

Prints the prolog (XML declaration + DTD + entity declarations) of a document.

Options: see C<L<flush> >.

=item prolog ($optional_filehandle, %options)

Returns the prolog (XML declaration + DTD + entity declarations) of a document.

Options: see C<L<flush> >.

=item finish

Calls the Expat C<finish> method.
Unsets all handlers (including internal ones that set context), but expat
continues parsing to the end of the document or until it finds an error.
It should finish a lot faster than with the handlers set.

=item finish_print

Stops twig processing, flush the twig, and proceed to finish printing the
document as fast as possible. Use this method when modifying a document and
the modification is done.

=item finish_now

Stops twig processing, does not finish parsing the document (which could
actually be not well-formed after the point where C<finish_now> is called).
Execution resumes after the C<Lparse>> or C<L<parsefile> > call. The content
of the twig is what has been parsed so far (all open elements at the time
C<finish_now> is called are considered closed).

=item set_expand_external_entities

Same as using the C<L<expand_external_ents> > option when creating the twig.

=item set_input_filter

Same as using the C<L<input_filter> > option when creating the twig.

=item set_keep_atts_order

Same as using the C<L<keep_atts_order> > option when creating the twig.

=item set_keep_encoding

Same as using the C<L<keep_encoding> > option when creating the twig.

=item escape_gt

Same as using the C<L<escape_gt> > option when creating the twig.

=item do_not_escape_gt

Reverts XML::Twig behavior to its default of not escaping > in its output.

lib/XML/Twig.pm  view on Meta::CPAN

are left untouched.

B<WARNING>: If you rely on IDs, then you will have to set the ID yourself. At
this point the element does not belong to a twig yet, so the ID attribute
is not known so it won't be stored in the ID list.

A content of 'C<#EMPTY>' creates an empty element.

=item namespace ($optional_prefix)

Returns the URI of the namespace that C<$optional_prefix> or the element name
belongs to. If the name doesn't belong to any namespace, C<undef> is returned.

=item local_name

Returns the local name (without the prefix) for the element.

=item ns_prefix

Returns the namespace prefix for the element.

=item current_ns_prefixes

Returns a list of namespace prefixes valid for the element. The order of the
prefixes in the list has no meaning. If the default namespace is currently
bound, then '' appears in the list.

=item inherit_att ($att, @optional_tag_list)

Returns the value of an attribute inherited from parent tags. The value
returned is found by looking for the attribute in the element then in turn
in each of its ancestors. If the C<@optional_tag_list> is supplied, then only those
ancestors whose tag is in the list will be checked.

=item all_children_are ($optional_condition)

Returns true (the calling element) if all children of the element pass the C<$optional_condition>,
false (0) otherwise.

=item level ($optional_condition)

Returns the depth of the element in the twig (root is 0).
If C<$optional_condition> is given then only ancestors that match the condition are
counted.

B<WARNING>: In a tree created using the C<twig_roots> option this will not return
the level in the document tree, level 0 will be the document root, level 1
will be the C<twig_roots> elements. During the parsing (in a C<twig_handler>)
you can use the C<depth> method on the twig object to get the real parsing depth.

=item in ($potential_parent)

Returns true (the potential parent element) if the element is in the potential_parent (C<$potential_parent> is
an element), otherwise false (0).

=item in_context ($cond, $optional_level)

Returns true (the matching including element) if the element is included in an element which passes C<$cond>
optionally within C<$optional_level> levels, otherwise false (0).

=item pcdata

Returns the text of a C<#PCDATA> element or C<undef> if the element is not
C<#PCDATA>.

=item pcdata_xml_string

Returns the text of a C<#PCDATA> element or C<undef> if the element is not C<#PCDATA>.
The text is "XML-escaped" ('&' and '<' are replaced by '&amp;' and '&lt;').

=item set_pcdata ($text)

Sets the text of a C<#PCDATA> element. This method does not check that the element is
indeed a C<#PCDATA> so usually you should use C<L<set_text> > instead.

=item append_pcdata ($text)

Adds the text at the end of a C<#PCDATA> element.

=item is_cdata

Returns true (1) if the element is a C<#CDATA> element, returns false ('') otherwise.

=item is_text

Returns true (1) if the element is a C<#CDATA> or C<#PCDATA> element, returns false ('') otherwise.

=item cdata

Returns the text of a C<#CDATA> element or C<undef> if the element is not
C<#CDATA>.

=item cdata_string

Returns the XML string of a C<#CDATA> element, including the opening and
closing markers.

=item set_cdata ($text)

Sets the text of a C<#CDATA> element.

=item append_cdata ($text)

Adds the text at the end of a C<#CDATA> element.

=item remove_cdata

Turns all C<#CDATA> sections in the element into regular C<#PCDATA> elements. This is useful
when converting XML to HTML, as browsers do not support CDATA sections.

=item extra_data

Returns the extra_data (comments and PI's) attached to an element.

=item set_extra_data ($extra_data)

Sets the extra_data (comments and PI's) attached to an element.

=item append_extra_data ($extra_data)

Appends extra_data to the existing extra_data before the element (if no
previous extra_data exists then it is created).

=item set_asis

Sets a property of the element that causes it to be output without being XML
escaped by the print functions: if it contains C<< a < b >> it will be output
as such and not as C<< a &lt; b >>. This can be useful to create text elements
that will be output as markup.

Note that all C<#PCDATA> descendants of the element are also marked as having
the property (they are the ones that are actually impacted by the change).

If the element is a C<#CDATA> element it will also be output asis, without the
C<#CDATA> markers. The same goes for any C<#CDATA> descendant of the element.

Returns the calling element.

=item set_not_asis

Unsets the C<asis> property for the element and its text descendants.

=item is_asis

Returns the C<asis> property status of the element (1 or C<undef>).

=item closed

Returns true if the element has been closed. Might be useful if you are
somewhere in the tree, during the parse, and have no idea whether a parent
element is completely loaded or not.

=item get_type

Returns the type of the element: 'C<#ELT>' for "real" elements, or 'C<#PCDATA>',
'C<#CDATA>', 'C<#COMMENT>', 'C<#ENT>', 'C<#PI>'.

=item is_elt

Returns the calling element if the element is a "real" element, or 0 if it is C<#PCDATA>,
C<#CDATA>...

=item contains_only_text

Returns true (the calling element) if the element does not contain any other "real" element, otherwise false (0).

=item contains_only ($exp)

Returns true (the list of matching children) if all children of the element match the expression C<$exp>, otherwise returns false (0).

  if( $para->contains_only( 'tt')) { ... }

=item contains_a_single ($exp)

Returns the (the matching child) if the element contains a single child that matches the expression C<$exp>,
otherwise returns false (0).

=item is_field

Same as C<contains_only_text>.

=item is_pcdata

Returns true (1) if the element is a C<#PCDATA> element, otherwise returns false ('').

=item is_ent

Returns true (1) if the element is an entity (an unexpanded entity) element,
otherwise returns false ('').

=item is_empty

Returns true (1) if the element is empty, otherwise returns false ('').

=item set_empty

Flags the element as empty. No further check is made, so if the element
is actually not empty the output will be messed. The only effect of this
method is that the output will be C<< <tag att="value""/> >>.

Returns the calling element.

=item set_not_empty

Flags the element as not empty. If it is actually empty then the element will
be output as C<< <tag att="value""></tag> >>.

Returns the calling element.

=item is_pi

Returns true (1) if the element is a processing instruction (C<#PI>) element,
otherwise returns false ('').

=item target

Returns the target of a processing instruction.

=item set_target ($target)

Sets the target of a processing instruction.

Returns the calling element.

=item data

Returns the data part of a processing instruction.

=item set_data ($data)

Sets the data of a processing instruction.

Returns the calling element.

=item set_pi ($target, $data)

Sets the target and data of a processing instruction.

Returns the calling element.

=item pi_string

lib/XML/Twig.pm  view on Meta::CPAN

Same as sprint.

=item xml_text

Returns the text of the element, encoded (and processed by the current
C<L<output_filter> > or C<L<output_encoding> > options, without any tag.

=item xml_text_only

Same as C<L<xml_text> > except that the text returned doesn't include
the text of sub-elements.

=item set_pretty_print ($style)

Sets the pretty print method, amongst 'C<none>' (default), 'C<nsgmls>',
'C<nice>', 'C<indented>', 'C<record>' and 'C<record_c>'.

pretty_print styles:

=over 4

=item none

the default, no C<\n> is used.

=item nsgmls

nsgmls style, with C<\n> added within tags.

=item nice

adds C<\n> wherever possible (NOT SAFE, can lead to invalid XML).

=item indented

Same as C<nice> plus indents elements (NOT SAFE, can lead to invalid XML).

=item record

table-oriented pretty print, one field per line.

=item record_c

table-oriented pretty print, more compact than C<record>, one record per line.

=back

Returns the previous setting.

=item set_empty_tag_style ($style)

Sets the method to output empty tags. Values are 'C<normal>' (default), 'C<html>',
and 'C<expand>'.

C<normal> outputs an empty tag 'C<< <tag/> >>', C<html> adds a space
'C<< <tag /> >>' for elements that can be empty in XHTML and C<expand> outputs
'C<< <tag></tag> >>'.

Returns the previous setting.

=item set_remove_cdata ($flag)

Sets (or unsets) the flag that forces the twig to output C<#CDATA> sections as
regular (escaped) C<#PCDATA>.

Returns the previous setting.

=item set_indent ($string)

Sets the indentation for the indented pretty print style (default is two spaces).

Returns the previous setting.

=item set_quote ($quote)

Sets the quotes used for attributes. Valid values are 'C<double>' (default) or 'C<single>'.

Returns the previous setting.

=item cmp ($elt)

  Compare the order of the two elements in a twig.

  C<$a> is the <A>..</A> element, C<$b> is the <B>...</B> element

  document                        $a->cmp( $b)
  <A> ... </A> ... <B>  ... </B>     -1
  <A> ... <B>  ... </B> ... </A>     -1
  <B> ... </B> ... <A>  ... </A>      1
  <B> ... <A>  ... </A> ... </B>      1
   $a == $b                           0
   $a and $b not in the same tree   undef

=item before ($elt)

Returns 1 if C<$elt> starts before the element, 0 otherwise. If the two elements
are not in the same twig then return C<undef>.

    if( $a->cmp( $b) == -1) { return 1; } else { return 0; }

=item after ($elt)

Returns 1 if $elt starts after the element, 0 otherwise. If the two elements
are not in the same twig then return C<undef>.

    if( $a->cmp( $b) == -1) { return 1; } else { return 0; }

=item other comparison methods

=over 4

=item lt

=item le

=item gt

=item ge

=back



( run in 0.742 second using v1.01-cache-2.11-cpan-39bf76dae61 )