TokeParser(3pm)

πŸ’– XML::TokeParser β€” TokeParser(3pm) πŸ’–

bestie. listen. This is the manual page for XML::TokeParser, coming at you from the User Contributed Perl Documentation, section 3pm. It's the simplified interface to XML::Parser and honestly? She ate. Let's get into it. ✨


πŸŽ€ NAME πŸŽ€

XML::TokeParser β€” it's a Simplified interface to XML::Parser. That's the whole vibe. That's the name.


✨ SYNOPSIS ✨

okay so here's the whole thing in code, no notes:

use XML::TokeParser;
                                                                        #
#parse from file
my $p = XML::TokeParser->new('file.xml')
                                                                        #
#parse from open handle
open IN, 'file.xml' or die $!;
my $p = XML::TokeParser->new( \*IN, Noempty => 1 );
                                                                        #
#parse literal text
my $text = '<tag xmlns="http://www.omsdev.com">text</tag>';
my $p    = XML::TokeParser->new( \$text, Namespaces => 1 );
                                                                        #
#read next token
my $token = $p->get_token();
                                                                        #
#skip to <title> and read text
$p->get_tag('title');
$p->get_text();
                                                                        #
#read text of next <para>, ignoring any internal markup
$p->get_tag('para');
$p->get_trimmed_text('/para');
                                                                        #
#process <para> if interesting text
$t = $p->get_tag('para');
$p->begin_saving($t);
if ( $p->get_trimmed_text('/para') =~ /interesting stuff/ ) {
    $p->restore_saved();
    process_para($p);
}

every single one of those comment blocks is exactly as written, don't @ me πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

XML::TokeParser gives you a procedural ("pull mode") interface to XML::Parser, much in the same way that Gisle Aas' HTML::TokeParser provides a procedural interface to HTML::Parser. It splits its XML input up into "tokens," where each token corresponds to an XML::Parser event. it's giving "same energy, different parser." πŸ”₯

A token is a bless'd reference to an array. First element? An event-type string. Last element? The literal text of the XML input that generated the event. And everything in the middle between those two? That varies depending on the event type β€” she's flexible like that. πŸ’

Each token is an object of type XML::TokeParser::Token. Go read "XML::TokeParser::Token" to find out what methods you can use to inspect the token and pull data out of it. iykyk. πŸ‘‘


πŸ’… METHODS πŸ’…

$p = XML::TokeParser->new($input, [options])

Makes you a brand new parser β€” you tell it the input source and any options you want. Here's the tea on $input:

  • If $input is a string, it's the name of the file to parse. πŸ“
  • If $input is a reference to a string, that string is the actual text to parse. πŸ“
  • If $input is a reference to a typeglob or an IO::Handle object corresponding to an open file or socket, then the text read from the handle will be parsed. πŸ”Œ

Options are name=>value pairs and can be literally any of these:

Namespaces

If set to a true value, namespace processing is enabled. slay. ✨

ParseParamEnt

This option is passed on to the underlying XML::Parser object β€” go read that module's documentation for the details, bestie, it's their info not mine. πŸ“š

Noempty

If set to a true value, text tokens that consist of only whitespace (like the ones created by indentation and line breaks in between tags) will be ignored. LOVE that for us. πŸ™ˆ

Latin

If set to a true value, all text other than the literal text elements of tokens gets translated into the ISO 8859-1 (Latin-1) character encoding instead of the normal UTF-8 encoding. 🌈

Catalog

The value here is the URI of a catalog file used to resolve PUBLIC and SYSTEM identifiers. See XML::Catalog for details. πŸ—‚οΈ


$token = $p->get_token()

Returns the next token from the input, as an array reference. And if there are no remaining tokens? It returns undef. that's it, that's the method. 🎬


$p->unget_token($token,...)

Pushes tokens back so they'll get re-read. Super useful if you've read one or more tokens too far. And yes β€” it correctly handles "partial" tokens returned by get_tag(). no cap. 🫢


$token = $p->get_tag( [$token] )

No argument? Then it skips tokens until it hits the next start tag or end tag token. Got an argument? Then it skips tokens until the start tag or end tag (if the argument begins with /) for the named element.

Heads up tho: the returned token does not include an event type code β€” its first element is the element name, and that name gets prefixed by a / if the token is for an end tag. πŸ‘€


$text = $p->get_text( [$token] )

No argument? It returns the text at the current position, or an empty string if the next token isn't a 'T' token. Argument given? Then it gathers up all text between the current position and the specified start or end tag, stripping out any intervening tags β€” much like the way a typical Web browser deals with unknown tags. fr fr. 🌸


$text = $p->get_trimmed_text( [$token] )

Like get_text(), but she deletes any leading or trailing whitespaces and collapses multiple whitespace (newlines included) into single spaces. tidy queen. πŸ§ΉπŸ’…


$p->begin_saving( [$token] )

Makes every subsequent call to get_token(), get_tag(), get_text(), and get_trimmed_text() save the returned tokens. Paired with restore_saved(), this lets you "back up" within a token stream. βͺ

And if you pass an argument? It gets placed at the beginning of the list of saved tokens β€” which is useful because you often won't know you want to start saving until you've already read the first token you want saved. (the struggle is real 😭)


$p->restore_saved()

Pushes all the tokens saved by begin_saving() back onto the token stream, and stops saving tokens. Wanna cancel saving without backing up? Just call begin_saving() and restore_saved() in succession. iconic. πŸŽ€


πŸ‘‘ XML::TokeParser::Token πŸ‘‘

A token is a blessed array reference, you get it from "$p->get_token" or "$p->get_tag", and it might look like:

["S",  $tag, $attr, $attrseq, $raw]
["E",  $tag, $raw]
["T",  $text, $raw]
["C",  $text, $raw]
["PI", $target, $data, $raw]

If you don't like remembering array indices (because you're a real programmer πŸ’…), you can access the attributes of a token like this:

"$t->tag", "$t->attr", "$t->attrseq", "$t->raw", "$t->text", "$t->target", "$t->data".

Please note that this may change in the future, where as there will be 4 token types, XML::TokeParser::Token::StartTag .... ⚠️ (not me warning you about the future in advance, bestie, pay attention)

πŸ€” What kind of token is it?

To find out, inspect your token using any of these is_* methods (1 == true, 0 == false, d'oh):

  • is_text
  • is_comment
  • is_pi which is short for is_process_instruction
  • is_start_tag
  • is_end_tag
  • is_tag

🧐 What's that token made of?

To retrieve data from your token, use any of the following methods, depending on the kind of token you have:

  • target β€” only for process instructions
  • data β€” only for process instructions
  • raw for all tokens
  • attr β€” only for start tags, returns a hashref ( print "#link ", "$t->attr"->{href} ).
  • my $attrseq = $t->attrseq β€” only for start tags, returns an array ref of the keys found in "$t->attr" in the order they originally appeared in.
  • my $tagname = $t->tag β€” only for tags ( print "opening ", "$t->tag" if "$t->is_start_tag" ).
  • my $text = $token->text β€” only for tokens of type text and comment

🌈 Here's more detailed info about the tokens. 🌈

  • Start tag β€” The token has five elements: 'S', the element's name, a reference to a hash of attribute values keyed by attribute names, a reference to an array of attribute names in the order in which they appeared in the tag, and the literal text.
  • End tag β€” The token has three elements: 'E', the element's name, and the literal text.
  • Character data (text) β€” The token has three elements: 'T', the parsed text, and the literal text. All contiguous runs of text are gathered into single tokens; there will never be two 'T' tokens in a row. periodt. πŸ’€
  • Comment β€” The token has three elements: 'C', the parsed text of the comment, and the literal text.
  • Processing instruction β€” The token has four elements: 'PI', the target, the data, and the literal text.

The literal text includes any markup delimiters (pointy brackets, <![CDATA[, etc.), entity references, and numeric character references β€” and it's in the XML document's original character encoding. All other text is in UTF-8 (unless the Latin option is set, in which case it's in ISO-8859-1) regardless of the original encoding, and all entity and character references are expanded. 🫢

If the Namespaces option is set, element and attribute names get prefixed by their (possibly empty) namespace URIs enclosed in curly brackets β€” and xmlns:* attributes do not appear in 'S' tokens. noted. πŸ“Œ


πŸ”₯ DIFFERENCES FROM HTML::TokeParser πŸ”₯

  • Uses a true XML parser rather than a modified HTML parser.
  • Text and comment tokens include extracted text as well as literal text.
  • PI tokens include target and data as well as literal text.
  • No tokens for declarations.
  • No "textify" hash.
  • unget_token correctly handles partial tokens returned by get_tag().
  • begin_saving() and restore_saved()

to be continued, bestie β€” there's more of this page coming πŸ’–

✨ EXAMPLES ✨ (the part where it all clicks, bestie)

Okay so here's a full lil program that shows every token type doing its thing. Watch and learn πŸ’…:

use XML::TokeParser;
use strict;
                                                                                      #
my $text = '<tag foo="bar" foy="floy"> some text <!--comment--></tag>';
my $p    = XML::TokeParser->new( \$text );
                                                                                      #
print $/;
                                                                                      #
while( defined( my $t = $p->get_token() ) ){
    local $\="\n";
    print '         raw = ', $t->raw;
                                                                                      #
    if( $t->tag ){
        print '         tag = ', $t->tag;
                                                                                      #
        if( $t->is_start_tag ) {
            print '        attr = ', join ',', %{$t->attr};
            print '     attrseq = ', join ',', @{$t->attrseq};
        }
                                                                                      #
        print 'is_tag       ', $t->is_tag;
        print 'is_start_tag ', $t->is_start_tag;
        print 'is_end_tag   ', $t->is_end_tag;
    }
    elsif( $t->is_pi ){
        print '      target = ', $t->target;
        print '        data = ', $t->data;
        print 'is_pi        ', $t->is_pi;
    }
    else {
        print '        text = ', $t->text;
        print 'is_text      ', $t->is_text;
        print 'is_comment   ', $t->is_comment;
    }
                                                                                      #
    print $/;
}
__END__

And the output it spits out? Absolute slay πŸ”₯:

             raw = <tag foo="bar" foy="floy">
             tag = tag
            attr = foo,bar,foy,floy
         attrseq = foo,foy
    is_tag       1
    is_start_tag 1
    is_end_tag   0

             raw =  some text
            text =  some text
    is_text      1
    is_comment   0

             raw = <!--comment-->
            text = comment
    is_text      0
    is_comment   1

             raw = </tag>
             tag = tag
    is_tag       1
    is_start_tag 0
    is_end_tag   1

πŸ› BUGS πŸ›

Found a glitch? Not the vibe, but okay, we handle it πŸ’–. To report bugs, go to <http://rt.cpan.org/NoAuth/Bugs.html?Dist=XML-TokeParser> or send mail to <bug-XML-Tokeparser@rt.cpan.org>.


πŸ‘‘ AUTHOR πŸ‘‘

Copyright (c) 2003 D.H. aka PodMaster (current maintainer). Copyright (c) 2001 Eric Bohlman (original author).

All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. If you don't know what this means, visit <http://perl.com/> or <http://cpan.org/>.


🌈 SEE ALSO 🌈

HTML::TokeParser, XML::Parser, XML::Catalog, XML::Smart, XML::Twig.


That's the whole page bestie, you ate it fr fr πŸ«ΆπŸ’– This lil legend lives at perl v5.40.1 and was dated 2025-03-07, filed under TokeParser(3pm). Go forth and parse, you gorgeous genius πŸ¦‹βœ¨

πŸ“¦ where this page comes from