Twig(3pm) | User Contributed Perl Documentation | Twig(3pm) |
XML::Twig - A perl module for processing huge XML documents in tree mode.
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 <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'); sub my_list_process { my( $twig, $list)= @_; # ... }
See XML::Twig 101 for other ways to use the module, as a filter for example.
This module provides a way to process XML documents. It is build on top of "XML::Parser".
The module offers a tree interface to the document, while allowing you to output the parts of it that have been completely processed.
It allows minimal resource (CPU and memory) usage by building the tree only for the parts of the documents that need actual processing, through the use of the "twig_roots " and "twig_print_outside_roots " options. The "finish " and "finish_print " methods also help to increase performances.
XML::Twig tries to make simple things easy so it tries its best to takes care of a lot of the (usually) annoying (but sometimes necessary) features that come with XML and XML::Parser.
XML::Twig comes with a few command-line utilities:
XML pretty printer using XML::Twig
"xml_grep" does a grep on XML files. Instead of using regular expressions it uses XPath expressions (in fact the subset of XPath supported by XML::Twig).
"xml_split" takes a (presumably big) XML file and split it in several smaller files, based on various criteria (level in the tree, size or an XPath expression)
"xml_merge" takes several xml files that have been split using "xml_split" and recreates a single file.
"xml_spellcheck" lets you spell check the content of an XML file. It extracts the text (the content of elements and optionally of attributes), call a spell checker on it and then recreates the XML document.
XML::Twig can be used either on "small" XML documents (that fit in memory) or on huge ones, by processing parts of the document and outputting or discarding them once they are processed.
my $t= XML::Twig->new(); $t->parse( '<d><title>title</title><para>p 1</para><para>p 2</para></d>'); my $root= $t->root; $root->set_tag( 'html'); # change doc to html $title= $root->first_child( 'title'); # get the title $title->set_tag( 'h1'); # turn it into h1 my @para= $root->children( 'para'); # get the para children foreach my $para (@para) { $para->set_tag( 'p'); } # turn them into p $t->print; # output the document
Other useful methods include:
att: "$elt->{'att'}->{'foo'}" return the "foo" attribute for an element,
set_att : "$elt->set_att( foo => "bar")" sets the "foo" attribute to the "bar" value,
next_sibling: "$elt->{next_sibling}" return the next sibling in the document (in the example "$title->{next_sibling}" is the first "para", you can also (and actually should) use "$elt->next_sibling( 'para')" to get it
The document can also be transformed through the use of the cut, copy, paste and move methods: "$title->cut; $title->paste( after => $p);" for example
And much, much more, see XML::Twig::Elt.
One of the strengths of XML::Twig is that it let you work with files that do not fit in memory (BTW storing an XML document in memory as a tree is quite memory-expensive, the expansion factor being often around 10).
To do this you can define handlers, that will be called once a specific element has been completely parsed. In these handlers you can access the element and process it as you see fit, using the navigation and the cut-n-paste methods, plus lots of convenient ones like "prefix ". Once the element is completely processed you can then "flush " it, which will output it and free the memory. You can also "purge " it if you don't need to output it (if you are just extracting some data from the document for example). The handler will be called again once the next relevant element has been parsed.
my $t= XML::Twig->new( twig_handlers => { section => \§ion, para => sub { $_->set_tag( 'p'); } }, ); $t->parsefile( 'doc.xml'); # the handler is called once a section is completely parsed, ie when # the end tag for section is found, it receives the twig itself and # the element (including all its sub-elements) as arguments sub section { my( $t, $section)= @_; # arguments for all twig_handlers $section->set_tag( 'div'); # change the tag name # let's use the attribute nb as a prefix to the title my $title= $section->first_child( 'title'); # find the title my $nb= $title->{'att'}->{'nb'}; # get the attribute $title->prefix( "$nb - "); # easy isn't it? $section->flush; # outputs the section and frees memory }
There is of course more to it: you can trigger handlers on more elaborate conditions than just the name of the element, "section/title" for example.
my $t= XML::Twig->new( twig_handlers => { 'section/title' => sub { $_->print } } ) ->parsefile( 'doc.xml');
Here "sub { $_->print }" simply prints the current element ($_ is aliased to the element in the handler).
You can also trigger a handler on a test on an attribute:
my $t= XML::Twig->new( twig_handlers => { 'section[@level="1"]' => sub { $_->print } } ); ->parsefile( 'doc.xml');
You can also use "start_tag_handlers " to process an element as soon as the start tag is found. Besides "prefix " you can also use "suffix ",
The twig_roots mode builds only the required sub-trees from the document Anything outside of the twig roots will just be ignored:
my $t= XML::Twig->new( # the twig will include just the root and selected titles twig_roots => { 'section/title' => \&print_n_purge, 'annex/title' => \&print_n_purge } ); $t->parsefile( 'doc.xml'); sub print_n_purge { my( $t, $elt)= @_; print $elt->text; # print the text (including sub-element texts) $t->purge; # frees the memory }
You can use that mode when you want to process parts of a documents but are not interested in the rest and you don't want to pay the price, either in time or memory, to build the tree for the it.
You can combine the "twig_roots" and the "twig_print_outside_roots" options to build filters, which let you modify selected elements and will output the rest of the document as is.
This would convert prices in $ to prices in Euro in a document:
my $t= XML::Twig->new( twig_roots => { 'price' => \&convert, }, # process prices twig_print_outside_roots => 1, # print the rest ); $t->parsefile( 'doc.xml'); sub convert { my( $t, $price)= @_; my $currency= $price->{'att'}->{'currency'}; # get the currency if( $currency eq 'USD') { $usd_price= $price->text; # get the price # %rate is just a conversion table my $euro_price= $usd_price * $rate{usd2euro}; $price->set_text( $euro_price); # set the new price $price->set_att( currency => 'EUR'); # don't forget this! } $price->print; # output the price }
XML::Twig is a lot more sensitive to variations in versions of perl, XML::Parser and expat than to the OS, so this should cover some reasonable configurations.
The "recommended configuration" is perl 5.8.3+ (for good Unicode support), XML::Parser 2.31+ and expat 1.95.5+
See <http://testers.cpan.org/search?request=dist&dist=XML-Twig> for the CPAN testers reports on XML::Twig, which list all tested configurations.
An Atom feed of the CPAN Testers results is available at <http://xmltwig.org/rss/twig_testers.rss>
Finally:
When in doubt, upgrade expat, XML::Parser and Scalar::Util
Finally, for some optional features, XML::Twig depends on some additional modules. The complete list, which depends somewhat on the version of Perl that you are running, is given by running "t/zz_dump_config.t"
You can also use "output_encoding" to convert the internal UTF-8 format to the required encoding.
XML::Twig provides the "safe_parse " and the "safe_parsefile " methods which wrap the parse in an eval and return either the parsed twig or 0 in case of failure.
XML::Twig uses a very limited number of classes. The ones you are most likely to use are "XML::Twig" of course, which represents a complete XML document, including the document itself (the root of the document itself is "root"), its handlers, its input or output filters... The other main class is "XML::Twig::Elt", which models an XML element. Element here has a very wide definition: it can be a regular element, or but also text, with an element "tag" of "#PCDATA" (or "#CDATA"), an entity (tag is "#ENT"), a Processing Instruction ("#PI"), a comment ("#COMMENT").
Those are the 2 commonly used classes.
You might want to look the "elt_class" option if you want to subclass "XML::Twig::Elt".
Attributes are just attached to their parent element, they are not objects per se. (Please use the provided methods "att" and "set_att" to access them, if you access them as a hash, then your code becomes implementation dependent and might break in the future).
Other classes that are seldom used are "XML::Twig::Entity_list" and "XML::Twig::Entity".
If you use "XML::Twig::XPath" instead of "XML::Twig", elements are then created as "XML::Twig::XPath::Elt"
A twig is a subclass of XML::Parser, so all XML::Parser methods can be called on a twig object, including parse and parsefile. "setHandlers" on the other hand cannot be used, see "BUGS "
New Options:
XPath expressions are limited to using the child and descendant axis (indeed you can't specify an axis), and predicates cannot be nested. You can use the "string", or "string(<tag>)" function (except in "twig_roots" triggers).
Additionally you can use regexps (/ delimited) to match attribute and string values.
Examples:
foo foo/bar foo//bar /foo/bar /foo//bar /foo/bar[@att1 = "val1" and @att2 = "val2"]/baz[@a >= 1] foo[string()=~ /^duh!+/] /foo[string(bar)=~ /\d+/]/baz[@att != 3]
#CDATA can be used to call a handler for a CDATA section. #COMMENT can be used to call a handler for comments
Some additional (non-XPath) expressions are also provided for convenience:
Expressions are evaluated against the input document. Which means that even if you have changed the tag of an element (changing the tag of a parent element from a handler for example) the change will not impact the expression evaluation. There is an exception to this: "private" attributes (which name start with a '#', and can only be created during the parsing, as they are not valid XML) are checked against the current twig.
Handlers are triggered in fixed order, sorted by their type (xpath expressions first, then regexps, then level), then by whether they specify a full path (starting at the root element) or not, then by number of steps in the expression, then number of predicates, then number of tests in predicates. Handlers where the last step does not specify a step ("foo/bar/*") are triggered after other XPath handlers. Finally "_all_" handlers are triggered last.
Important: once a handler has been triggered if it returns 0 then no other handler is called, except a "_all_" handler which will be called anyway.
If a handler returns a true value and other handlers apply, then the next applicable handler will be called. Repeat, rinse, lather..; The exception to that rule is when the "do_not_chain_handlers" option is set, in which case only the first handler will be called.
Note that it might be a good idea to explicitly return a short true value (like 1) from handlers: this ensures that other applicable handlers are called even if the last statement for the handler happens to evaluate to false. This might also speedup the code by avoiding the result of the last statement of the code to be copied and passed to the code managing handlers. It can really pay to have 1 instead of a long string returned.
When the closing tag for an element is parsed the corresponding handler is called, with 2 arguments: the twig and the "Element ". The twig includes the document tree that has been built so far, the element is the complete sub-tree for the element. The fact that the handler is called only when the closing tag for the element is found means that handlers for inner elements are called before handlers for outer elements.
$_ is also set to the element, so it is easy to write inline handlers like
para => sub { $_->set_tag( 'p'); }
Text is stored in elements whose tag name is #PCDATA (due to mixed content, text and sub-element in an element there is no way to store the text as just an attribute of the enclosing element, this is similar to the DOM model).
Warning: if you have used purge or flush on the twig the element might not be complete, some of its children might have been entirely flushed or purged, and the start tag might even have been printed (by "flush") already, so changing its tag might not give the expected result.
Example: my $t= XML::Twig->new( twig_roots => { title => 1, subtitle => 1}); $t->parsefile( file); my $t= XML::Twig->new( twig_roots => { 'section/title' => 1}); $t->parsefile( file);
return a twig containing a document including only "title" and "subtitle" elements, as children of the root element.
You can use generic_attribute_condition, attribute_condition, full_path, partial_path, tag, tag_regexp, _default_ and _all_ to trigger the building of the twig. string_condition and regexp_condition cannot be used as the content of the element, and the string, have not yet been parsed when the condition is checked.
WARNING: path are checked for the document. Even if the "twig_roots" option is used they will be checked against the full document tree, not the virtual tree created by XML::Twig
WARNING: twig_roots elements should NOT be nested, that would hopelessly confuse XML::Twig ;--(
Note: you can set handlers (twig_handlers) using twig_roots
Example: my $t= XML::Twig->new( twig_roots
=>
{ title => sub { $_[1]->print;},
subtitle => \&process_subtitle
}
);
$t->parsefile( file);
Example: my $t= XML::Twig->new( twig_roots => { title => \&number_title }, twig_print_outside_roots => 1, ); $t->parsefile( file); { my $nb; sub number_title { my( $twig, $title); $nb++; $title->prefix( "$nb "); $title->print; } }
This example prints the document outside of the title element, calls "number_title" for each "title" element, prints it, and then resumes printing the document. The twig is built only for the "title" elements.
If the value is a reference to a file handle then the document outside the "twig_roots" elements will be output to this file handle:
open( my $out, '>', 'out_file.xml') or die "cannot open out file.xml out_file:$!"; my $t= XML::Twig->new( twig_roots => { title => \&number_title }, # default output to $out twig_print_outside_roots => $out, ); { my $nb; sub number_title { my( $twig, $title); $nb++; $title->prefix( "$nb "); $title->print( $out); # you have to print to \*OUT here } }
You can use generic_attribute_condition, attribute_condition, full_path, partial_path, tag, tag_regexp, _default_ and _all_ to trigger the handler.
string_condition and regexp_condition cannot be used as the content of the element, and the string, have not yet been parsed when the condition is checked.
The main uses for those handlers are to change the tag name (you might have to do it as soon as you find the open tag if you plan to "flush" the twig at some point in the element, and to create temporary attributes that will be used when processing sub-element with "twig_hanlders".
Note: "start_tag" handlers can be called outside of "twig_roots" if this argument is used. Since the element object is not built, in this case handlers are called with the following arguments: $t (the twig), $tag (the tag of the element) and %att (a hash of the attributes of the element).
If the "twig_print_outside_roots" argument is also used, if the last handler called returns a "true" value, then the start tag will be output as it appeared in the original document, if the handler returns a "false" value then the start tag will not be printed (so you can print a modified string yourself for example).
Note that you can use the ignore method in "start_tag_handlers" (and only there).
twig_handlers are called when an element is completely parsed, so why have this redundant option? There is only one use for "end_tag_handlers": when using the "twig_roots" option, to trigger a handler for an element outside the roots. It is for example very useful to number titles in a document using nested sections:
my @no= (0); my $no; my $t= XML::Twig->new( start_tag_handlers => { section => sub { $no[$#no]++; $no= join '.', @no; push @no, 0; } }, twig_roots => { title => sub { $_->prefix( $no); $_->print; } }, end_tag_handlers => { section => sub { pop @no; } }, twig_print_outside_roots => 1 ); $t->parsefile( $file);
Using the "end_tag_handlers" argument without "twig_roots" will result in an error.
Note that the "_all_" handler will still be called regardless
Example:
my $twig= XML::Twig->new( ignore_elts => { elt => 'discard' }); $twig->parsefile( 'doc.xml');
This will build the complete twig for the document, except that all "elt" elements (and their children) will be left out.
The keys in the hash are triggers, limited to the same subset as "start_tag_handlers". The values can be "discard", to discard the element, "print", to output the element as-is, "string" to store the text of the ignored element(s), including markup, in a field of the twig: "$t->{twig_buffered_string}" or a reference to a scalar, in which case the text of the ignored element(s), including markup, will be stored in the scalar. Any other value will be treated as "discard".
The subroutine receives the string as argument, and returns the modified string:
# WE WANT ALL STRINGS IN UPPER CASE sub my_char_handler { my( $text)= @_; $text= uc( $text); return $text; }
This option is needed because during the parsing of the XML, elements are created by "XML::Twig", without any control from the user code.
See the "t/test6.t" test file to see what results you can expect from the various encoding options.
WARNING: if the original encoding is multi-byte then attribute parsing will be EXTREMELY unsafe under any Perl before 5.6, as it uses regular expressions which do not deal properly with multi-byte characters. You can specify an alternate function to parse the start tags with the "parse_start_tag" option (see below)
WARNING: this option is NOT used when parsing with XML::Parser non-blocking parser ("parse_start", "parse_more", "parse_done" methods) which you probably should not use with XML::Twig anyway as they are totally untested!
Pre-defined filters:
my $conv = XML::Twig::encode_convert( 'latin1'); my $t = XML::Twig->new(output_filter => $conv);
my $conv = XML::Twig::iconv_convert( 'latin1'); my $t = XML::Twig->new(output_filter => $conv);
my $conv = XML::Twig::unicode_convert( 'latin1'); my $t = XML::Twig->new(output_filter => $conv);
The "text" and "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 "XML::Twig::foo").
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 "<!ENTITY xxe PUBLIC "bar" "/etc/passwd">" to make the password fiel available in the document.
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 "name", "sysid" and "pubid" will be stored in the twig as "$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.
WARNING: setting expand_external_ents to 0 or -1 currently doesn't work as expected; cf. <https://rt.cpan.org/Public/Bug/Display.html?id=118097>. To completelty turn off expanding external entities use "no_xxe".
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 "DTD Handling" for more information
The exact algorithm to drop spaces is: strings including only spaces (perl \s) and at least one \n right before an open or close tag are dropped.
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. see the difference by calling the following code with 0 and 1 as arguments:
perl -MXML::Twig -e'print XML::Twig->new( keep_spaces => shift)->parse( "<d> \n<e/></d>")->_dump'
"keep_spaces" and "discard_spaces" cannot be both set.
The syntax for using this argument is:
XML::Twig->new( discard_spaces_in => [ 'elt1', 'elt2']);
The syntax for using this argument is:
XML::Twig->new( keep_spaces_in => [ 'elt1', 'elt2']);
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.
pretty_print formats:
This is quite ugly but better than "none", and it is very safe, the document will still be valid (conforming to its DTD).
This is how the SGML parser "sgmls" splits documents, hence the name.
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 "foo" element including a "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 "foo" tag as a sign that the element contains PCDATA, it will then die when it finds the "bar" tag. This may or may not be important for you, but be aware of it!
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 "keep_atts_order" option.
"normal" outputs an empty tag '"<tag/>"', "html" adds a space '"<tag />"' for elements that can be empty in XHTML and "expand" outputs '"<tag></tag>"'
Comments processing options:
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 "print" or "sprint" will return the comments in the text. Using "text" or "field" on the other hand will not.
Any use of "set_pcdata" on the "#PCDATA" element (directly or through other methods like "set_content") will delete the comment(s).
Consider using "process" if you are outputting SAX events from XML::Twig.
Note that you can also set PI handlers in the "twig_handlers" option:
'?' => \&handler '?target' => \&handler 2
The handlers will be called with 2 parameters, the twig and the PI element if "pi" is set to "process", and with 3, the twig, the target and the data if "pi" is set to "keep". Of course they will not be called if "pi" is set to "drop".
If "pi" is set to "keep" the handler should return a string that will be used as-is as the PI text (it should look like "" <?target data?" >" or '' if you want to remove the PI),
Only one handler will be called, "?target" or "?" if no specific handler for that target is available.
Here is an 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"/> </doc>
my $t= XML::Twig->new( map_xmlns => {'http://www.w3.org/2000/svg' => "svg"}, twig_handlers => { 'svg:circle' => sub { $_->set_att( r => 20) } }, keep_original_prefix => 1, 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:gr="http://www.w3.org/2000/svg"> <gr:circle cx="10" cy="90" r="20"/> </doc>
example:
# using an array ref my $t= XML::Twig->new( index => [ 'div', 'table' ]) ->parsefile( "foo.xml"); my $divs= $t->index( 'div'); my $first_div= $divs->[0]; my $last_table= $t->index( table => -1); # using a hashref to name the indexes my $t= XML::Twig->new( index => { email => 'a[@href=~/^ \s*mailto:/]'}) ->parsefile( "foo.xml"); my $last_emails= $t->index( email => -1);
Note that the index is not maintained after the parsing. If elements are deleted, renamed or otherwise hurt during processing, the index is NOT updated. (changing the id element OTOH will update the index)
my $t= XML::Twig->new( att_accessors => [ 'href', 'src']) ->parsefile( $file); my $first_href= $t->first_elt( 'img')->src; # same as ->att( 'src') $t->first_elt( 'img')->src( 'new_logo.png') # changes the attribute value
the list of accessors to create can be given 1 2 different
ways: in an array, or in a hash alias => expression
my $t= XML::Twig->new( elt_accessors => [
'head'])
->parsefile( $file);
my $title_text=
$t->root->head->field( 'title');
# same as $title_text=
$t->root->first_child( 'head')->field(
'title');
my $t= XML::Twig->new( elt_accessors => { warnings => 'p[@class="warning"]', d2 => 'div[2]'}, ) ->parsefile( $file); my $body= $t->first_elt( 'body'); my @warnings= $body->warnings; # same as $body->children( 'p[@class="warning"]'); my $s2= $body->d2; # same as $body->first_child( 'div[2]')
my $t= XML::Twig->new( field_accessors => [ 'h1']) ->parsefile( $file); my $div_title_text= $t->first_elt( 'div')->title; # same as $title_text= $t->first_elt( 'div')->field( 'title');
Note: I _HATE_ the Java-like name of arguments used by most XML modules. So in pure TIMTOWTDI fashion all arguments can be written either as "UglyJavaLikeName" or as "readable_perl_name": "twig_print_outside_roots" or "TwigPrintOutsideRoots" (or even "twigPrintOutsideRoots" {shudder}). XML::Twig normalizes them before processing them.
A die call is thrown if a parse error occurs. Otherwise it will return the twig built by the parse. Use "safe_parse" if you want the parsing to return even when an error occurs.
If this method is called as a class method ("XML::Twig->parse( $some_xml_or_html)") then an XML::Twig object is created, using the parameters except the last one (eg "XML::Twig->parse( pretty_print => 'indented', $some_xml_or_html)") and "xparse" is called on it.
Note that when parsing a filehandle, the handle should NOT be open with an encoding (ie open with "open( my $in, '<', $filename)". The file will be parsed by "expat", so specifying the encoding actually causes problems for the parser (as in: it can crash it, see https://rt.cpan.org/Ticket/Display.html?id=78877). For parsing a file it is actually recommended to use "parsefile" on the file name, instead of <parse> on the open file.
A "die" call is thrown if a parse error occurs. Otherwise it will return the twig built by the parse. Use "safe_parsefile" if you want the parsing to return even when an error occurs.
If an extension is given then the original file is backed-up (the rules for the extension are the same as the rule for the -i option in perl).
For most (read "small") XML it is probably as efficient (and easier to debug) to just "get" the XML file and then parse it as a string.
use XML::Twig; use LWP::Simple; my $twig= XML::Twig->new(); $twig->parse( LWP::Simple::get( $URL ));
or
use XML::Twig; my $twig= XML::Twig->nparse( $URL);
If the $optional_user_agent argument is used then it is used, otherwise a new one is created.
Note that the parsing still stops as soon as an error is detected, there is no way to keep going after an error.
Note that the parsing still stops as soon as an error is detected, there is no way to keep going after an error.
This works nicely, but some information gets lost in the process: newlines are removed, and (at least on the version I use), comments get an extra CDATA section inside ( <!-- foo --> becomes <!-- <![CDATA[ foo ]]> -->
this method is to be used with caution though, as it doesn't know about the file encoding, it is usually better to use "parse_html", which gives you a chance to open the file with the proper encoding layer.
Note that this is mostly a convenience method for one-off scripts. For example files that end in '.htm' or '.html' are parsed first as XML, and if this fails as HTML. This is certainly not the most efficient way to do this in general.
Examples:
XML::Twig->nparse( "file.xml"); XML::Twig->nparse( error_context => 1, "file://file.xml");
If the argument is not present, return an arrayref to the index
See "BUGS "
flush take an optional filehandle as an argument.
If you use "flush" at any point during parsing, the document will be flushed one last time at the end of the parsing, to the proper filehandle.
options: use the "update_DTD" option if you have updated the (internal) DTD and/or the entity list and you want the updated DTD to be output
The "pretty_print" option sets the pretty printing of the document.
Example: $t->flush( Update_DTD => 1); $t->flush( $filehandle, pretty_print => 'indented'); $t->flush( \*FILE);
options: see flush.
options: see "flush".
options: see "flush".
This is a bit safer when 2 processes an potentiallywrite the same file: only the last one will succeed, but the file won't be corruted. I often use this for cron jobs, so testing the code doesn't interfere with the cron job running at the same time.
options: see "flush".
options: see "flush".
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 any more for it and what has already been built will be deleted).
WARNING: the pretty print style is a GLOBAL variable, so once set it's applied to ALL "print"'s (and "sprint"'s). Same goes if you use XML::Twig with "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.
"normal" outputs an empty tag '"<tag/>"', "html" adds a space '"<tag />"' for elements that can be empty in XHTML and "expand" outputs '"<tag></tag>"'
options: see "flush".
options: see "flush".
Supported types and options:
Example:
$t->add_stylesheet( xsl => "xsl_style.xsl");
will generate the following PI at the beginning of the document:
<?xml-stylesheet type="text/xsl" href="xsl_style.xsl"?>
Inherited methods are:
(this method is broken on some versions of expat/XML::Parser)
If the $optional_array_ref argument is used the array must contain elements. The $xpath expression is applied to each element in turn and the result is union of all results. This way a first query can be refined in further steps.
Reclaims properly the memory used by an XML::Twig object. As the object has circular references it never goes out of scope, so if you want to parse lots of XML documents then the memory leak becomes a problem. Use "$twig->dispose" to clear this problem.
$elt->foo; # equivalent to $elt->{'att'}->{'foo'}; $elt->foo( 'bar'); # equivalent to $elt->set_att( foo => 'bar');
The methods are l-valued only under those perl's that support this feature (5.6 and above)
$elt->foo; # equivalent to $elt->first_child( 'foo');
$elt->foo; # equivalent to $elt->field( 'foo');
Examples: my $elt= XML::Twig::Elt->new(); my $elt= XML::Twig::Elt->new( para => { align => 'center' }); my $elt= XML::Twig::Elt->new( para => { align => 'center' }, 'foo'); my $elt= XML::Twig::Elt->new( br => '#EMPTY'); my $elt= XML::Twig::Elt->new( 'para'); my $elt= XML::Twig::Elt->new( para => 'this is a para'); my $elt= XML::Twig::Elt->new( para => $elt3, 'another para');
The strings are not parsed, the element is not attached to any twig.
WARNING: if you rely on ID's 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.
Note that "#COMMENT", "#PCDATA" or "#CDATA" are valid tag names, that will create text elements.
To create an element "foo" containing a CDATA section:
my $foo= XML::Twig::Elt->new( '#CDATA' => "content of the CDATA section") ->wrap_in( 'foo');
An attribute of '#CDATA', will create the content of the element as CDATA:
my $elt= XML::Twig::Elt->new( 'p' => { '#CDATA' => 1}, 'foo < bar');
creates an element
<p><![CDATA[foo < bar]]></>
As obviously the element does not exist beforehand this method has to be called on the class:
my $elt= parse XML::Twig::Elt( "<a> string to parse, with <sub/> <elements>, actually tons of </elements> h</a>");
The print outputs XML data so base entities are escaped.
options: see "flush". =item sprint ($elt, $optional_no_enclosing_tag)
Return the xml string for an entire element, including the tags. If the optional second argument is true then only the string inside the element is returned (the start and end tag for $elt are not). The text is XML-escaped: base entities (& and < in text, & < and " in attribute values) are turned into entities.
"tag" and "name" are synonyms of "gi".
Similar methods are available for the other navigation methods:
All this methods also exist in "trimmed" variant:
Same method as "first_child_text" with a different name
If no child matches $condition _and_ if $condition is a valid XML element name, then a new element by that name is created and inserted as the last child.
if( $elt->first_child_matches( 'title')) ...
is equivalent to
if( $elt->{first_child} && $elt->{first_child}->passes( 'title'))
"first_child_is" is another name for this method
Similar methods are available for the other navigation methods:
The $optional_elt is the root of a subtree. When the "next_elt" is out of the subtree then the method returns undef. You can then walk a sub-tree with:
my $elt= $subtree_root; while( $elt= $elt->next_elt( $subtree_root)) { # insert processing code here }
In scalar context, returns the concatenation of the text of children of the element
In scalar context, returns the concatenation of the trimmed text of children of the element
NOTE: the element itself is not part of the list, in order to include it you will have to use ancestors_or_self
this method is an lvalue, so you can do "$elt->latt( 'foo')= 'bar'" or "$elt->latt( 'foo')++;"
You can actually set several attributes this way:
$elt->set_att( att1 => "val1", att2 => "val2");
You can actually delete several attributes at once:
$elt->del_att( 'att1', 'att2', 'att3');
Note that the "old" links to the parent, previous and next siblings can still be accessed using the former_* methods
This makes it easier to write loops where you cut elements:
my $child= $parent->first_child( 'achild'); while( $child->{'att'}->{'cut'}) { $child->cut; $child= ($child->{former} && $child->{former}->{next_sibling}); }
Return the list of children
Return the list of descendants
Note that the calling element is pasted:
$child->paste( first_child => $existing_parent); $new_sibling->paste( after => $this_sibling_is_already_in_the_tree);
or
my $new_elt= XML::Twig::Elt->new( tag => $content); $new_elt->paste( $position => $existing_elt);
Example:
my $t= XML::Twig->new->parse( 'doc.xml') my $toc= $t->root->new( 'toc'); $toc->paste( $t->root); # $toc is pasted as first child of the root foreach my $title ($t->findnodes( '/doc/section/title')) { my $title_toc= $title->copy; # paste $title_toc as the last child of toc $title_toc->paste( last_child => $toc) }
Position options:
Note that you can call directly the underlying method:
If the option is "asis" then the prefix is added asis: it is created in a separate "PCDATA" element with an "asis" property. You can then write:
$elt1->prefix( '<b>', 'asis');
to create a "<b>" in the output of "print".
If the option is "asis" then the suffix is added asis: it is created in a separate "PCDATA" element with an "asis" property. You can then write:
$elt2->suffix( '</b>', 'asis');
Note that in some cases you can still end up with multiple spaces, if they are split between several elements:
<doc> text <b> hah! </b> yep</doc>
gets trimmed to
<doc>text <b> hah! </b> yep</doc>
This is somewhere in between a bug and a feature.
Note: there is no magic here, if you write "$twig->parsefile( $file )->simplify();" then it will load the entire document in memory. I am afraid you will have to put some work into it to get just the bits you want and discard the rest. Look at the synopsis or the XML::Twig 101 section at the top of the docs for more information.
This option allows variables in the XML to be expanded when the file is read. (there is no facility for putting the variable names back if you regenerate XML using XMLout).
A 'variable' is any text of the form ${name} (or $name) which occurs in an attribute value or in the text content of an element. If 'name' matches a key in the supplied hashref, ${name} will be replaced with the corresponding value from the hashref. If no matching key is found, the variable will not be replaced.
<dirs> <dir name="prefix">/usr/local</dir> <dir name="exec_prefix">$prefix/bin</dir> </dirs>
use "var => 'name'" to get $prefix replaced by /usr/local in the generated data structure
By default variables are captured by the following regexp: /$(\w+)/
If the element is:
<config host="laptop.xmltwig.org"> <server>localhost</server> <dirs> <dir name="base">/home/mrodrigu/standards</dir> <dir name="tools">$base/tools</dir> </dirs> <templates> <template name="std_def">std_def.templ</template> <template name="dummy">dummy</template> </templates> </config>
Then calling simplify with "group_tags => { dirs => 'dir', templates => 'template'}" makes the data structure be exactly as if the start and end tags for "dirs" and "templates" were not there.
A YAML dump of the structure
base: '/home/mrodrigu/standards' host: laptop.xmltwig.org server: localhost template: - std_def.templ - dummy.templ tools: '$base/tools'
If the element is not a text element then the first text child of the element is split
if $elt is "<p>tati tata <b>tutu tati titi</b> tata tati tata</p>"
$elt->split( qr/(ta)ti/, 'foo', {type => 'toto'} )
will change $elt to
<p><foo type="toto">ta</foo> tata <b>tutu <foo type="toto">ta</foo> titi</b> tata <foo type="toto">ta</foo> tata</p>
The regexp can be passed either as a string or as "qr//" (perl 5.005 and later), it defaults to \s+ just as the "split" built-in (but this would be quite a useless behaviour without the $optional_tag parameter)
$optional_tag defaults to PCDATA or CDATA, depending on the initial element type
The list of descendants is returned (including un-touched original elements and newly created ones)
The $regexp_string includes tags, within pointy brackets, as in "<title><para>+" and the usual Perl modifiers (+*?...). Tags can be further qualified with attributes: "<para type="warning" classif="cosmic_secret">+". The values for attributes should be xml-escaped: "<candy type="M&Ms">*" ("<", "&" ">" and """ should be escaped).
Note that elements might get extra "id" attributes in the process. See add_id. Use strip_att to remove unwanted id's.
Here is an example:
If the element $elt has the following content:
<elt> <p>para 1</p> <l_l1_1>list 1 item 1 para 1</l_l1_1> <l_l1>list 1 item 1 para 2</l_l1> <l_l1_n>list 1 item 2 para 1 (only para)</l_l1_n> <l_l1_n>list 1 item 3 para 1</l_l1_n> <l_l1>list 1 item 3 para 2</l_l1> <l_l1>list 1 item 3 para 3</l_l1> <l_l1_1>list 2 item 1 para 1</l_l1_1> <l_l1>list 2 item 1 para 2</l_l1> <l_l1_n>list 2 item 2 para 1 (only para)</l_l1_n> <l_l1_n>list 2 item 3 para 1</l_l1_n> <l_l1>list 2 item 3 para 2</l_l1> <l_l1>list 2 item 3 para 3</l_l1> </elt>
Then the code
$elt->wrap_children( q{<l_l1_1><l_l1>*} , li => { type => "ul1" }); $elt->wrap_children( q{<l_l1_n><l_l1>*} , li => { type => "ul" }); $elt->wrap_children( q{<li type="ul1"><li type="ul">+}, "ul"); $elt->strip_att( 'id'); $elt->strip_att( 'type'); $elt->print;
will output:
<elt> <p>para 1</p> <ul> <li> <l_l1_1>list 1 item 1 para 1</l_l1_1> <l_l1>list 1 item 1 para 2</l_l1> </li> <li> <l_l1_n>list 1 item 2 para 1 (only para)</l_l1_n> </li> <li> <l_l1_n>list 1 item 3 para 1</l_l1_n> <l_l1>list 1 item 3 para 2</l_l1> <l_l1>list 1 item 3 para 3</l_l1> </li> </ul> <ul> <li> <l_l1_1>list 2 item 1 para 1</l_l1_1> <l_l1>list 2 item 1 para 2</l_l1> </li> <li> <l_l1_n>list 2 item 2 para 1 (only para)</l_l1_n> </li> <li> <l_l1_n>list 2 item 3 para 1</l_l1_n> <l_l1>list 2 item 3 para 2</l_l1> <l_l1>list 2 item 3 para 3</l_l1> </li> </ul> </elt>
$regexp must be a perl regexp, created with the "qr" operator.
$replace can include "$1, $2"... from the $regexp. It can also be used to create element and entities, by using "&elt( tag => { att => val }, text)" (similar syntax as "new") and "&ent( name)".
Here is a rather complex example:
$elt->subs_text( qr{(?<!do not )link to (http://([^\s,]*))}, 'see &elt( a =>{ href => $1 }, $2)' );
This will replace text like link to http://www.xmltwig.org by see <a href="www.xmltwig.org">www.xmltwig.org</a>, but not do not link to...
Generating entities (here replacing spaces with ):
$elt->subs_text( qr{ }, '&ent( " ")');
or, using a variable:
my $ent=" "; $elt->subs_text( qr{ }, "&ent( '$ent')");
Note that the substitution is always global, as in using the "g" modifier in a perl substitution, and that it is performed on all text descendants of the element.
Bug: in the $regexp, you can only use "\1", "\2"... if the replacement expression does not include elements or attributes. eg
$t->subs_text( qr/((t[aiou])\2)/, '$2'); # ok, replaces toto, tata, titi, tutu by to, ta, ti, tu $t->subs_text( qr/((t[aiou])\2)/, '&elt(p => $1)' ); # NOK, does not find toto...
The id is an attribute, "id" by default, see the "id" option for XML::Twig "new" to change it. Use an id starting with "#" to get an id that's not output by print, flush or sprint, yet that allows you to use the elt_id method to get the element easily.
If the element already has an id, no new id is generated.
By default the method create an id of the form "twig_id_<nnnn>", where "<nnnn>" is a number, incremented each time the method is called successfully.
Return the element
Return the element, with its children sorted.
%options are
type : numeric | alpha (default: alpha) order : normal | reverse (default: normal)
Return the element, with its children sorted
Return the element.
Return the element, with its children sorted
For example:
$elt->sort_children( sub { $_[0]->{'att'}->{"nb"} + $_[0]->text }, type => 'numeric', order => 'reverse' );
The sub-element is then cut.
A subset of the XPATH abbreviated syntax is covered:
tag tag[1] (or any other positive number) tag[last()] tag[@att] (the attribute exists for the element) tag[@att="val"] tag[@att=~ /regexp/] tag[att1="val1" and att2="val2"] tag[att1="val1" or att2="val2"] tag[string()="toto"] (returns tag elements which text (as per the text method) is toto) tag[string()=~/regexp/] (returns tag elements which text (as per the text method) matches regexp) expressions can start with / (search starts at the document root) expressions can start with . (search starts at the current element) // can be used to get all descendants instead of just direct children * matches any tag
So the following examples from the XPath recommendation<http://www.w3.org/TR/xpath.html#path-abbrev> work:
para selects the para element children of the context node * selects all element children of the context node para[1] selects the first para child of the context node para[last()] selects the last para child of the context node */para selects all para grandchildren of the context node /doc/chapter[5]/section[2] selects the second section of the fifth chapter of the doc chapter//para selects the para element descendants of the chapter element children of the context node //para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node //olist/item selects all the item elements in the same document as the context node that have an olist parent .//para selects the para element descendants of the context node .. selects the parent of the context node para[@type="warning"] selects all para children of the context node that have a type attribute with value warning employee[@secretary and @assistant] selects all the employee children of the context node that have both a secretary attribute and an assistant attribute
The elements will be returned in the document order.
If $optional_offset is used then only one element will be returned, the one with the appropriate offset in the list, starting at 0
Quoting and interpolating variables can be a pain when the Perl syntax and the XPATH syntax collide, so use alternate quoting mechanisms like q or qq (I like q{} and qq{} myself).
Here are some more examples to get you started:
my $p1= "p1"; my $p2= "p2"; my @res= $t->get_xpath( qq{p[string( "$p1") or string( "$p2")]}); my $a= "a1"; my @res= $t->get_xpath( qq{//*[@att="$a"]}); my $val= "a1"; my $exp= qq{//p[ \@att='$val']}; # you need to use \@ or you will get a warning my @res= $t->get_xpath( $exp);
Note that the only supported regexps delimiters are / and that you must backslash all / in regexps AND in regular strings.
XML::Twig does not provide natively full XPATH support, but you can use "XML::Twig::XPath" to get "findnodes" to use "XML::XPath" as the XPath engine, with full coverage of the spec.
"XML::Twig::XPath" to get "findnodes" to use "XML::XPath" as the XPath engine, with full coverage of the spec.
The '"no_recurse"' option will only return the text of the element, not of any included sub-elements (same as "text_only").
$p->insert( table => { border=> 1}, 'tr', 'td')
put $p in a table with a visible border, a single "tr" and a single "td" and return the "table" element:
<p><table border="1"><tr><td>original content of p</td></tr></table></p>
Optionally each tag can be followed by a hashref of attributes, that will be set on the wrapping element:
$elt->wrap_in( p => { class => "advisory" }, div => { class => "intro", id => "div_intro" });
Return the newly created element
The $optional_atts argument is the ref of a hash of attributes. If this argument is used then the previous attributes are deleted, otherwise they are left untouched.
WARNING: if you rely on ID's 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 '"#EMPTY"' creates an empty element;
WARNING: in a tree created using the "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 "twig_roots" elements. During the parsing (in a "twig_handler") you can use the "depth" method on the twig object to get the real parsing depth.
If the element is a "CDATA" element it will also be output asis, without the "CDATA" markers. The same goes for any "CDATA" descendant of the element
if( $para->contains_only( 'tt')) { ... }
Note that an XML comment cannot start or end with a '-', or include '--' (http://www.w3.org/TR/2008/REC-xml-20081126/#sec-comments), if that is the case (because you have created the comment yourself presumably, as it could not be in the input XML), then a space will be inserted before an initial '-', after a trailing one or between two '-' in the comment (which could presumably mangle javascript "hidden" in an XHTML comment);
If the $optional_condition is given then only siblings that match the condition are counted. If the element itself does not match the condition then 0 is returned.
You can also pass a list instead of a hashref: "$elt->set_atts( att1 => 'val1',...)"
The options are passed as a hashref, setting "escape_gt" to a true value will also escape '>' ($elt( 'myatt', { escape_gt => 1 });
Note that classes are then sorted alphabetically, so the "class" attribute can be changed even if the class is already there
Note that classes are then sorted alphabetically, so the "class" attribute can be changed even if the class is already there
The '"no_recurse"' option will only return the text of the element, not of any included sub-elements (same as "xml_text_only").
pretty_print styles:
"normal" outputs an empty tag '"<tag/>"', "html" adds a space '"<tag />"' for elements that can be empty in XHTML and "expand" outputs '"<tag></tag>"'
Compare the order of the 2 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
if( $a->cmp( $b) == -1) { return 1; } else { return 0; }
if( $a->cmp( $b) == -1) { return 1; } else { return 0; }
It looks like "/doc/sect[3]/title": unique elements do not have an index, the others do.
Those methods should not be used, unless of course you find some creative and interesting, not to mention useful, ways to do it.
Most of the navigation functions accept a condition as an optional argument The first element (or all elements for "children " or "ancestors ") that passes the condition is returned.
The condition is a single step of an XPath expression using the XPath subset defined by "get_xpath". Additional conditions are:
The condition can be
XML::Twig implements a subset of XPath through the "get_xpath" method.
If you want to use the whole XPath power, then you can use "XML::Twig::XPath" instead. In this case "XML::Twig" uses "XML::XPath" to execute XPath queries. You will of course need "XML::XPath" installed to be able to use "XML::Twig::XPath".
See XML::XPath for more information.
The methods you can use are:
In order for "XML::XPath" to be used as the XPath engine the following methods are included in "XML::Twig":
in XML::Twig
in XML::Twig::Elt
The methods you can use are the same as on "XML::Twig::XPath" elements:
Additional examples (and a complete tutorial) can be found on the XML::Twig Page<http://www.xmltwig.org/xmltwig/>
To figure out what flush does call the following script with an XML file and an element name as arguments
use XML::Twig; my ($file, $elt)= @ARGV; my $t= XML::Twig->new( twig_handlers => { $elt => sub {$_[0]->flush; print "\n[flushed here]\n";} }); $t->parsefile( $file, ErrorContext => 2); $t->flush; print "\n";
Useful methods:
There are 3 possibilities here. They are:
If you use the load_DTD option when creating the twig the DTD information and the entity declarations can be accessed.
The DTD and the entity declarations will be "flush"'ed (or "print"'ed) either as is (if they have not been modified) or as reconstructed (poorly, comments are lost, order is not kept, due to it's content this DTD should not be viewed by anyone) if they have been modified. You can also modify them directly by changing the "$twig->{twig_doctype}->{internal}" field (straight from XML::Parser, see the "Doctype" handler doc)
If you use the "load_DTD" when creating the twig the DTD information and the entity declarations can be accessed. The entity declarations will be "flush"'ed (or "print"'ed) either as is (if they have not been modified) or as reconstructed (badly, comments are lost, order is not kept).
You can change the doctype through the
"$twig->set_doctype" method and
print the dtd through the
"$twig->dtd_text" or
"$twig->dtd_print"
methods.
If you need to modify the entity list this is probably the easiest way to do it.
Remember that element handlers are called when the element is CLOSED, so if you have handlers for nested elements the inner handlers will be called first. It makes it for example trickier than it would seem to number nested sections (or clauses, or divs), as the titles in the inner sections are handled before the outer sections.
This is due to a bug in the way weak references are handled in Perl itself.
The fix is either to upgrade to Perl 5.16 or later ("perlbrew" is a great tool to manage several installations of perl on the same machine).
Another, NOT RECOMMENDED, way of fixing the problem, is to switch off weak references by writing "XML::Twig::_set_weakrefs( 0);" at the top of the code. This is totally unsupported, and may lead to other problems though,
Basically you can read the DTD, output it back properly, and update entities, but not much more.
So use XML::Twig with standalone documents, or with documents referring to an external DTD, but don't expect it to properly parse and even output back the DTD.
If you create elements the same thing might happen, use the "delete" method to get rid of them.
Alternatively installing the "Scalar::Util" (or "WeakRef") module on a version of Perl that supports it (>5.6.0) will get rid of the memory leaks automagically.
$twig->change_gi( $old1, $new); $twig->change_gi( $old2, $new); $twig->change_gi( $new, $even_newer);
Also there is an unavoidable bug when using "flush" and pretty printing for elements with mixed content that start with an embedded element:
<elt><b>b</b>toto<b>bold</b></elt> will be output as <elt> <b>b</b>toto<b>bold</b></elt>
if you flush the twig when you find the "<b>" element
These are the things that can mess up calling code, especially if threaded. They might also cause problem under mod_perl.
PCDATA return '#PCDATA' CDATA return '#CDATA' PI return '#PI', I had the choice between PROC and PI :--(
%base_ent= ( '>' => '>', '<' => '<', '&' => '&', "'" => ''', '"' => '"', ); CDATA_START = "<![CDATA["; CDATA_END = "]]>"; PI_START = "<?"; PI_END = "?>"; COMMENT_START = "<!--"; COMMENT_END = "-->";
pretty print styles
( $NSGMLS, $NICE, $INDENTED, $INDENTED_C, $WRAPPED, $RECORD1, $RECORD2)= (1..7);
empty tag output style
( $HTML, $EXPAND)= (1..2);
$empty_tag_style can mess up HTML bowsers though and changing $ID would most likely create problems.
$pretty=0; # pretty print style $quote='"'; # quote for attributes $INDENT= ' '; # indent for indented pretty print $empty_tag_style= 0; # how to display empty tags $ID # attribute used as an id ('id' by default)
%gi2index; # tag => index @index2gi; # list of tags
If you need to manipulate all those values, you can use the following methods on the XML::Twig object:
The hash has the following fields: "pretty", "quote", "indent", "empty_tag_style", "keep_encoding", "expand_external_entities", "output_filter", "output_text_filter", "keep_atts_order"
A future version will try to support this while trying not to be to hard on performance (at least when a single twig is used!).
Michel Rodriguez <mirod@cpan.org>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Bug reports should be sent using: RT <http://rt.cpan.org/NoAuth/Bugs.html?Dist=XML-Twig>
Comments can be sent to mirod@cpan.org
The XML::Twig page is at <http://www.xmltwig.org/xmltwig/> It includes the development version of the module, a slightly better version of the documentation, examples, a tutorial and a: Processing XML efficiently with Perl and XML::Twig: <http://www.xmltwig.org/xmltwig/tutorial/index.html>
Complete docs, including a tutorial, examples, an easier to use HTML version of the docs, a quick reference card and a FAQ are available at <http://www.xmltwig.org/xmltwig/>
git repository at <http://github.com/mirod/xmltwig>
XML::Parser, XML::Parser::Expat, XML::XPath, Encode, Text::Iconv, Scalar::Utils
XML::Twig is not the only XML::Processing module available on CPAN (far from it!).
The main alternative I would recommend is XML::LibXML.
Here is a quick comparison of the 2 modules:
XML::LibXML, actually "libxml2" on which it is based, sticks to the standards, and implements a good number of them in a rather strict way: XML, XPath, DOM, RelaxNG, I must be forgetting a couple (XInclude?). It is fast and rather frugal memory-wise.
XML::Twig is older: when I started writing it XML::Parser/expat was the only game in town. It implements XML and that's about it (plus a subset of XPath, and you can use XML::Twig::XPath if you have XML::XPathEngine installed for full support). It is slower and requires more memory for a full tree than XML::LibXML. On the plus side (yes, there is a plus side!) it lets you process a big document in chunks, and thus let you tackle documents that couldn't be loaded in memory by XML::LibXML, and it offers a lot (and I mean a LOT!) of higher-level methods, for everything, from adding structure to "low-level" XML, to shortcuts for XHTML conversions and more. It also DWIMs quite a bit, getting comments and non-significant whitespaces out of the way but preserving them in the output for example. As it does not stick to the DOM, is also usually leads to shorter code than in XML::LibXML.
Beyond the pure features of the 2 modules, XML::LibXML seems to be preferred by "XML-purists", while XML::Twig seems to be more used by Perl Hackers who have to deal with XML. As you have noted, XML::Twig also comes with quite a lot of docs, but I am sure if you ask for help about XML::LibXML here or on Perlmonks you will get answers.
Note that it is actually quite hard for me to compare the 2 modules: on one hand I know XML::Twig inside-out and I can get it to do pretty much anything I need to (or I improve it ;--), while I have a very basic knowledge of XML::LibXML. So feature-wise, I'd rather use XML::Twig ;--). On the other hand, I am painfully aware of some of the deficiencies, potential bugs and plain ugly code that lurk in XML::Twig, even though you are unlikely to be affected by them (unless for example you need to change the DTD of a document programmatically), while I haven't looked much into XML::LibXML so it still looks shinny and clean to me.
That said, if you need to process a document that is too big to fit memory and XML::Twig is too slow for you, my reluctant advice would be to use "bare" XML::Parser. It won't be as easy to use as XML::Twig: basically with XML::Twig you trade some speed (depending on what you do from a factor 3 to... none) for ease-of-use, but it will be easier IMHO than using SAX (albeit not standard), and at this point a LOT faster (see the last test in <http://www.xmltwig.org/article/simple_benchmark/>).
2020-07-21 | perl v5.30.3 |