XML::TreePP(3pm)
β¨ NAME β¨
okay so bestie, meet XML::TreePP β the Pure Perl implementation for parsing/writing XML documents. This page is XML::TreePP(3pm), and it is lowkey here to make XML feel less cursed. π¦
π¦ SYNOPSIS π¦
parse an XML document from file into hash tree:
use XML::TreePP;
my $tpp = XML::TreePP->new();
my $tree = $tpp->parsefile( "index.rdf" );
print "Title: ", $tree->{"rdf:RDF"}->{item}->[0]->{title}, "\n";
print "URL: ", $tree->{"rdf:RDF"}->{item}->[0]->{link}, "\n";
write an XML document as string from hash tree:
use XML::TreePP;
my $tpp = XML::TreePP->new();
my $tree = { rss => { channel => { item => [ {
title => "The Perl Directory",
link => "http://www.perl.org/",
}, {
title => "The Comprehensive Perl Archive Network",
link => "http://cpan.perl.org/",
} ] } } };
my $xml = $tpp->write( $tree );
print $xml;
get a remote XML document by HTTP-GET and parse it into hash tree:
use XML::TreePP;
my $tpp = XML::TreePP->new();
my $tree = $tpp->parsehttp( GET => "http://use.perl.org/index.rss" );
print "Title: ", $tree->{"rdf:RDF"}->{channel}->{title}, "\n";
print "URL: ", $tree->{"rdf:RDF"}->{channel}->{link}, "\n";
get a remote XML document by HTTP-POST and parse it into hash tree:
use XML::TreePP;
my $tpp = XML::TreePP->new( force_array => [qw( item )] );
my $cgiurl = "http://search.hatena.ne.jp/keyword";
my $keyword = "ajax";
my $cgiquery = "mode=rss2&word=".$keyword;
my $tree = $tpp->parsehttp( POST => $cgiurl, $cgiquery );
print "Link: ", $tree->{rss}->{channel}->{item}->[0]->{link}, "\n";
print "Desc: ", $tree->{rss}->{channel}->{item}->[0]->{description}, "\n";
πΈ DESCRIPTION πΈ
XML::TreePP parses an XML document and expands it for a hash tree. It also does the opposite glow-up: generates an XML document from a hash tree. It is a pure Perl implementation and requires no modules depended. It can also fetch and parse an XML document from a remote web server like the XMLHttpRequest object does at JavaScript language. β¨
π EXAMPLES π
π Parse XML file π
Sample XML document:
<?xml version="1.0" encoding="UTF-8"?>
<family name="Kawasaki">
<father>Yasuhisa</father>
<mother>Chizuko</mother>
<children>
<girl>Shiori</girl>
<boy>Yusuke</boy>
<boy>Kairi</boy>
</children>
</family>
Sample program to read a xml file and dump it:
use XML::TreePP;
use Data::Dumper;
my $tpp = XML::TreePP->new();
my $tree = $tpp->parsefile( "family.xml" );
my $text = Dumper( $tree );
print $text;
Result dumped:
$VAR1 = {
'family' => {
'-name' => 'Kawasaki',
'father' => 'Yasuhisa',
'mother' => 'Chizuko',
'children' => {
'girl' => 'Shiori'
'boy' => [
'Yusuke',
'Kairi'
],
}
}
};
Details:
print $tree->{family}->{father}; # the father's given name.
The prefix '-' is added on every attribute's name.
print $tree->{family}->{"-name"}; # the family name of the family
The array is used because the family has two boys.
print $tree->{family}->{children}->{boy}->[1]; # The second boy's name
print $tree->{family}->{children}->{girl}; # The girl's name
π Text node and attributes π
If a element has both of a text node and attributes or both of a text node and other child nodes, value of a text node is moved to "#text" like child nodes.
use XML::TreePP;
use Data::Dumper;
my $tpp = XML::TreePP->new();
my $source = '<span class="author">Kawasaki Yusuke</span>';
my $tree = $tpp->parse( $source );
my $text = Dumper( $tree );
print $text;
The result dumped is following:
$VAR1 = {
'span' => {
'-class' => 'author',
'#text' => 'Kawasaki Yusuke'
}
};
The special node name of "#text" is used because this elements has attribute(s) in addition to the text node. See also "text_node_key" option. π
π METHODS π
π new π
This constructor method returns a new XML::TreePP object with %options.
$tpp = XML::TreePP->new( %options );
π set π
This method sets a option value for "option_name". If $option_value is not defined, its option is deleted.
$tpp->set( option_name => $option_value );
See OPTIONS section below for details.
π get π
This method returns a current option value for "option_name".
$tpp->get( 'option_name' );
π parse π
This method reads an XML document by string and returns a hash tree converted. The first argument is a scalar or a reference to a scalar.
$tree = $tpp->parse( $source );
π parsefile π
This method reads an XML document by file and returns a hash tree converted. The first argument is a filename.
$tree = $tpp->parsefile( $file );
π parsehttp π
This method receives an XML document from a remote server via HTTP and returns a hash tree converted.
$tree = $tpp->parsehttp( $method, $url, $body, $head );
$method is a method of HTTP connection: GET/POST/PUT/DELETE. $url is an URI of an XML file. $body is a request body when you use POST method. $head is a request headers as a hash ref. LWP::UserAgent module or HTTP::Lite module is required to fetch a file.
( $tree, $xml, $code ) = $tpp->parsehttp( $method, $url, $body, $head );
In array context, This method returns also raw XML document received and HTTP response's status code. π«Ά
π write π
This method parses a hash tree and returns an XML document as a string.
$source = $tpp->write( $tree, $encode );
$tree is a reference to a hash tree.
π writefile π
This method parses a hash tree and writes an XML document into a file.
$tpp->writefile( $file, $tree, $encode );
$file is a filename to create. $tree is a reference to a hash tree.
π₯ OPTIONS FOR PARSING XML π₯
This module accepts option parameters following:
β¨ force_array β¨
This option allows you to specify a list of element names which should always be forced into an array representation.
$tpp->set( force_array => [ 'rdf:li', 'item', '-xmlns' ] );
The default value is null, it means that context of the elements will determine to make array or to keep it scalar or hash. Note that the special wildcard name '*' means all elements.
β¨ force_hash β¨
This option allows you to specify a list of element names which should always be forced into an hash representation.
$tpp->set( force_hash => [ 'item', 'image' ] );
The default value is null, it means that context of the elements will determine to make hash or to keep it scalar as a text node. See also "text_node_key" option below. Note that the special wildcard name '*' means all elements.
β¨ cdata_scalar_ref β¨
This option allows you to convert a cdata section into a reference for scalar on parsing an XML document.
$tpp->set( cdata_scalar_ref => 1 );
The default value is false, it means that each cdata section is converted into a scalar.
β¨ user_agent β¨
This option allows you to specify a HTTP_USER_AGENT string which is used by parsehttp() method.
$tpp->set( user_agent => 'Mozilla/4.0 (compatible; ...)' );
The default string is 'XML-TreePP/#.##', where '#.##' is substituted with the version number of this library.
β¨ http_lite β¨
This option forces parsehttp() method to use a HTTP::Lite instance.
my $http = HTTP::Lite->new();
$tpp->set( http_lite => $http );
β¨ lwp_useragent β¨
This option forces parsehttp() method to use a LWP::UserAgent instance.
my $ua = LWP::UserAgent->new();
$ua->timeout( 60 );
$ua->env_proxy;
$tpp->set( lwp_useragent => $ua );
You may use this with LWP::UserAgent::WithCache.
β¨ base_class β¨
This blesses class name for each element's hashref. Each class is named straight as a child class of it parent class.
$tpp->set( base_class => 'MyElement' );
my $xml = '<root><parent><child key="val">text</child></parent></root>';
my $tree = $tpp->parse( $xml );
print ref $tree->{root}->{parent}->{child}, "\n";
A hash for <child> element above is blessed to "MyElement::root::parent::child" class. You may use this with Class::Accessor.
β¨ elem_class β¨
This blesses class name for each element's hashref. Each class is named horizontally under the direct child of "MyElement".
$tpp->set( base_class => 'MyElement' );
my $xml = '<root><parent><child key="val">text</child></parent></root>';
my $tree = $tpp->parse( $xml );
print ref $tree->{root}->{parent}->{child}, "\n";
A hash for <child> element above is blessed to "MyElement::child" class.
β¨ xml_deref β¨
This option dereferences the numeric character references, like ë, 漢, etc., in an XML document when this value is true.
$tpp->set( xml_deref => 1 );
Note that, for security reasons and your convenient, this module dereferences the predefined character entity references, &, <, >, ' and ", and the numeric character references up to U+007F without xml_deref per default. π₯
β¨ require_xml_decl β¨
This option requires XML declaration at the top of XML document to parse.
$tpp->set( require_xml_decl => 1 );
This will die when <?xml .../?> declration not found. π
βοΈ OPTIONS FOR WRITING XML βοΈ
okay bestie now we're on the output side π these options control how your precious little tree gets turned back into XML. slay.
πΈ first_out
This one lets you say "these specific element and attribute names go FIRST, idc, they're the main character." β¨
$tpp->set( first_out => [ 'link', 'title', '-type' ] );
The default value is null, which means alphabetical order is used. boring but valid ngl π
π last_out
Same energy, opposite direction β give it a list of element/attribute names that should always show up last in the output XML document. π¦
$tpp->set( last_out => [ 'items', 'item', 'entry' ] );
π indent
Makes the output actually readable by humans by indenting appropriately. we love a glow-up. β¨
$tpp->set( indent => 2 );
lowkey important: this does not strictly follow the XML specification β but it does look nice. it's giving aesthetic over compliance, and honestly? iconic. π«Ά
π¦ xml_decl
By default this module inserts an XML declaration on top of the XML document it generates. This option forces it to change to another one, or just remove it entirely. π
$tpp->set( xml_decl => '' );
π output_encoding
Lets you specify the encoding of the XML document generated by the write/writefile methods. π
$tpp->set( output_encoding => 'UTF-8' );
- On Perl 5.8.0 and later, you can pick from every encoding supported by
Encode.pm. the whole buffet fr fr β¨ - On Perl 5.6.x and before with
Jcode.pm, you can use"Shift_JIS","EUC-JP","ISO-2022-JP"and"UTF-8".
The default value is "UTF-8", which is the recommended encoding. periodt. π
π empty_element_tag_end
$tpp->set( empty_element_tag_end => '>' );
Sets the characters that close an empty tag. The default value is ' />'. tiny detail, big vibes π
π OPTIONS FOR BOTH π
the multitalented options that show up for both parsing AND writing. dual threat behavior, we stan π
π« utf8_flag
Turns the utf8 flag on for every element's value that gets parsed, and turns it on for the XML document generated as well. β¨
$tpp->set( utf8_flag => 1 );
Perl 5.8.1 or later is required to use this. no 5.8.0 girlies, sorry π
π attr_prefix
Lets you specify a prefix character (or characters!) that gets inserted before each attribute name. π¦
$tpp->set( attr_prefix => '@' );
- The default character is
'-'. - Or set
'@'to access attribute values like E4X, ECMAScript for XML. very fancy of you β¨ - A zero-length prefix
''is available as well β that means no prefix is added at all. naked attributes, scandalous π
π text_node_key
Lets you specify the hash key used for text nodes.
$tpp->set( text_node_key => '#text' );
The default key is "#text". iykyk πΈ
π¨ ignore_error
By default, this module calls the Carp::croak function whenever there's an error. This option makes ALL errors get ignored, and it just returns. π
$tpp->set( ignore_error => 1 );
like bestie... no error handling? okay go off I guess π
π’ use_ixhash
This option keeps the order for each element as it appeared in the XML. The Tie::IxHash module is required. π
$tpp->set( use_ixhash => 1 );
ngl this makes parsing performance slow β about 100% slower than default. you're trading speed for order, choose your fighter π
π AUTHOR
Yusuke Kawasaki, http://www.kawa.net/
π₯ REPOSITORY
https://github.com/kawanet/XML-TreePP
πΈ COPYRIGHT
The following copyright notice applies to all the files provided in this distribution, including binary files, unless explicitly noted otherwise.
Copyright 2006-2010 Yusuke Kawasaki
π LICENSE
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
and that's the whole page bestie, we made it π«Άβ¨ this was perl v5.36.0, dated 2022-10-13, and the page is XML::TreePP(3pm). go forth and parse, you absolute icon π
π
π¦ where this page comes from
- ubuntu noble: libxml-treepp-perl 0.43-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libxml-treepp-perl 0.43-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libxml-treepp-perl 0.43-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms