Twig(3)
Hey bestie, welcome to Twig(3) β a page from User Contributed Perl Documentation π
πΈ NAME πΈ
XML::Twig β a perl module for processing huge XML documents in tree mode. Thatβs the whole vibe β¨
π¦ SYNOPSIS π¦
Okay so real talk: this documentation is intended as a reference to the module.
The 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 π«Ά
π DESCRIPTION π
This module provides a way to process XML documents. It is built 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 take care of a lot of the (usually) annoying (but sometimes necessary) features that come with XML and XML::Parser πβ¨
π οΈ TOOLS π οΈ
XML::Twig comes with a few command-line utilities:
π xml_pp - xml pretty-printer π
XML pretty printer using XML::Twig.
πΈ xml_grep - grep XML files looking for specific elements πΈ
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 - cut a big XML file into smaller chunks π¦
xml_split takes a (presumably big) XML file and splits it into several smaller files, based on various criteria (level in the tree, size or an XPath expression).
π xml_merge - merge back XML files split with xml_split π
xml_merge takes several xml files that have been split using xml_split and recreates a single file.
π₯ xml_spellcheck - spellcheck XML files π₯
xml_spellcheck lets you spell check the content of an XML file. It extracts the text (the content of elements and optionally of attributes), calls a spell checker on it and then recreates the XML document.
π XML::Twig 101 π
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.
π Loading an XML document and processing it π
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')returns thefooattribute for an element.set_att:$elt->set_att( foo => "bar")sets thefooattribute to thebarvalue.next_sibling:$elt->next_siblingreturns the next sibling in the document (in the example$title->next_siblingis the firstpara; 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 π
π¦ Processing an XML document chunk by chunk π¦
One of the strengths of XML::Twig is that it lets 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,
π Processing just parts of an XML document π
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 document 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 it.
π₯ Building an XML filter π₯
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 and various versions of Perl, XML::Parser and expat β
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:
- XML::Twig does NOT work with expat 1.95.4
- XML::Twig only works with XML::Parser 2.27 in perl 5.6.*
- Note that I canβt compile XML::Parser 2.27 anymore, so I canβt guarantee that it still works
- XML::Parser 2.28 does not really work
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 π§
π¦ Simplifying XML processing π¦
β¨ Whitespaces β¨
Okay so whitespace that looks non-significant gets discarded β this behavior is controlled with the keep_spaces , keep_spaces_in , and discard_spaces_in options. Slay.
πΈ Encoding πΈ
You can specify that you want the output in the same encoding as the input β provided you have valid XML, which means you have to specify the encoding either in the document or when you create the Twig object β using the keep_encoding option. No cap.
You can also use output_encoding to convert the internal UTF-8 format to the required encoding. Very demure, very mindful.
π¬ Comments and Processing Instructions (PI) π¬
Comments and PIβs can be hidden from the processing, but still appear in the output β they are carried by the "real" element closer to them. Iconic behavior, honestly.
π Pretty Printing π
XML::Twig can output the document pretty printed so it is easier to read for us humans. Bestie, our eyeballs deserve it.
π Surviving an untimely death π
XML parsers are supposed to react violently when fed improper XML. XML::Parser just dies. Dramatic much?
XML::Twig provides the safe_parse and safe_parsefile methods which wrap the parse in an eval and return either the parsed twig or 0 in case of failure. So you donβt have to fully panic. π
π Private attributes π
Attributes with a name starting with # (illegal in XML) will not be output, so you can safely use them to store temporary values during processing. Note that you can store anything in a private attribute, not just text β itβs just a regular Perl variable, so a reference to an object or a huge data structure is perfectly fine. Main character storage unit energy. π«Ά
π CLASSES π
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. Short list, big power. β¨
You might want to look at 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). Lowkey important, bestie.
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.
π METHODS π
XML::Twig
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. Okay so noted.
π new π
This is a class method, the constructor for XML::Twig. Options are passed as keyword value pairs. Recognized options are the same as XML::Parser, plus some (in fact a lot!) XML::Twig specifics.
New Options:
twig_handlers β this argument consists of a hash { expression =" \&handler}> where expression is an XPath-like expression (+ some others).
- 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, orstring(<tag>)function (except intwig_rootstriggers). - 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:
- processing instructions β
'?'or'#PI'triggers the handler for any processing instruction, and'?<target>'or'#PI <target>'triggers a handler for processing instruction with the given target (ex:'#PI xml-stylesheet'). level(<level>)β triggers the handler on any element at that level in the tree (root is level 1)._all_β triggers the handler for all elements in the tree._default_β triggers the handler for each element that does NOT have any other handler.
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. Fr fr.
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. So likeβ¦ be careful, bestie. π
twig_roots β this argument letβs you build the tree only for those elements you are interested in.
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);
twig_print_outside_roots β to be used in conjunction with the twig_roots argument. When set to a true value this will print the document outside of the twig_roots elements.
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. Obsessed with the efficiency. π
β¨
If the value is a reference to a file handle, then everything outside the twig_roots elements gets output to that file handle, bestie:
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
}
}
π start_tag_handlers π
A hash { expression => \&handler}. It sets element handlers that fire when the element is open (like, at the end of the XML::Parser "Start" handler). Your handler gets 2 params: the twig and the element. Heads up though β the element is empty at that point, its attributes are created though. So it's giving "just walked in, hasn't unpacked yet" energy π
You can trigger the handler with generic_attribute_condition, attribute_condition, full_path, partial_path, tag, tag_regexp, _default_ and _all_.
string_condition and regexp_condition cannot be used as the content of the element, and the string has not yet been parsed when the condition is checked. Just so you know π
The main uses for these 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-elements with twig_handlers (the manpage spells it twig_hanlders β an iconic typo, we stan anyway π«Ά).
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, then if the last handler called returns a true value, 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). Your call, main character β¨
Note that you can use the ignore method in start_tag_handlers (and only there). Literally only there. Nowhere else. Obsessed with the exclusivity.
π¦ end_tag_handlers π¦
A hash { expression => \&handler}. Sets element handlers that are called when the element is closed (at the end of the XML::Parser "End" handler). These handlers are called with 2 params: the twig and the tag of the element.
Now, twig_handlers are called when an element is completely parsed, so why have this redundant option? Valid question, bestie, and there is literally 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 theend_tag_handlersargument withouttwig_rootswill result in an error. Not a warning, not a gentle nudge β an error. So don't π
πΈ do_not_chain_handlers πΈ
If this option is set to a true value, then only one handler will be called for each element, even if several satisfy the condition.
Note that the _all_ handler will still be called regardless. She always shows up. Queen behavior π
π ignore_elts π
This option lets you ignore elements when building the twig. Super useful in cases where you cannot use twig_roots to ignore elements β for example if the element to ignore is a sibling of elements you are interested in. Awkward sibling situation, we've all been there π
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. Poof, gone, no notes β¨
The keys in the hash are triggers, limited to the same subset as start_tag_handlers. The values can be:
discardβ to discard the elementprintβ to output the element as-isstringβ to store the text of the ignored element(s), including markup, in a field of the twig:$t->{twig_buffered_string}- 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. So don't get cute with it π
π§ char_handler π§
A reference to a subroutine that will be called every time PCDATA is found.
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;
}
Yelling in all caps, on purpose, in the code. Iconic π₯
π css_sel π
When set to a true value, allows selectors tag.class in handlers.
Okay so the dot is a valid character in element names β e.g. div.header is a completely valid XML name. So nothing's broken, it's just ambiguous vibes.
But since XML::Twig is used quite a bit to process XHTML, and HTML based dialects, it is quite convenient to be able to use div.header to trigger on a div element with a class header, instead of the more cumbersome div[@class=~/\bheader\b/]. Like, look at that regex. Exhausting. π
Note that the tag.class syntax is supported in navigation expressions, unless css_sel is explicitly set to 0.
π elt_class π
The name of a class used to store elements. This class should inherit from XML::Twig::Elt (and by default it is XML::Twig::Elt). This option is used to subclass the element class and extend it with new methods.
This option is needed because during the parsing of the XML, elements are created by XML::Twig, without any control from the user code. So you literally cannot sneak your own constructor in there β hence the option. Slay for foresight π
β keep_atts_order β
Setting this option to a true value causes the attribute hash to be tied to a Tie::IxHash object.
This means that Tie::IxHash needs to be installed for this option to be available. It also means that the hash keeps its order, so you will get the attributes in order. This allows outputting the attributes in the same order as they were in the original document. Chaos-free attribute output, we love to see it π«Ά
π keep_encoding π
This is a (slightly?) evil option: if the XML document is not UTF-8 encoded and you want to keep it that way, then setting keep_encoding will use the Expat original_string method for character, thus keeping the original encoding, as well as the original entities in the strings.
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). Extremely unsafe!! Not me being dramatic, the manpage said it first π
WARNING: this option is NOT used when parsing with XML::Parser non-blocking parser (parse_start,parse_more,parse_donemethods) which you probably should not use with XML::Twig anyway as they are totally untested! Totally. Untested. Ma'am. π
π output_encoding π
This option generates an output_filter using Encode, Text::Iconv or Unicode::Map8 and Unicode::Strings, and sets the encoding in the XML declaration. This is the easiest way to deal with encodings β if you need more sophisticated features, look at output_filter below. Set it and forget it, bestie β¨
π¦ output_filter π¦
This option is used to convert the character encoding of the output document. It is passed either a string corresponding to a predefined filter or a subroutine reference. The filter will be called every time a document or element is processed by the print functions (print, sprint, flush).
Pre-defined filters:
anya latin1 anya
Uses either Encode, Text::Iconv or Unicode::Map8 and Unicode::String or a regexp (which works only with XML::Parser 2.27), in this order, to convert all characters to ISO-8859-15 (usually latin1 is synonym to ISO-8859-1, but in practice it seems that ISO-8859-15, which includes the euro sign, is more useful and probably what most people want). Euro sign rights πΆβ¨
html
Does the same conversion as latin1, plus encodes entities using HTML::Entities (oddly enough you will need to have HTML::Entities installed for it to be available). This should only be used if the tags and attribute names themselves are in US-ASCII, or they will be converted and the output will not be valid XML any more. So valid-XML girlies, check your tags first π
safe
Converts the output to ASCII (US) only plus character entities (&#nnn;) β this should be used only if the tags and attribute names themselves are in US-ASCII, or they will be converted and the output will not be valid XML any more.
safe_hex
Same as safe except that the character entities are in hex (&#xnnn;). Little hex moment. Hex girlies rise π§
encode_convert ($encoding)
Return a subref that can be used to convert utf8 strings to $encoding. Uses Encode.
my $conv = XML::Twig::encode_convert( 'latin1');
my $t = XML::Twig->new(output_filter => $conv);
iconv_convert ($encoding)β this one makes you a filter subroutine that converts characters to your target encoding usingText::Iconv(so yeah, that module needs to be installed β peep its docs and theiconvlibrary docs to see which encodings your system actually has;iconv -lshould hand you the full list) π
my $conv = XML::Twig::iconv_convert( 'latin1');
my $t = XML::Twig->new(output_filter => $conv);
unicode_convert ($encoding)β this function makes a filter subroutine that converts characters to the target encoding usingUnicode::StringsandUnicode::Map8(both of which need to be installed β check the module docs to find out which encodings are available on your machine) β¨
my $conv = XML::Twig::unicode_convert( 'latin1');
my $t = XML::Twig->new(output_filter => $conv);
Okay so important thing bestie: the text and att methods do not use the filter, so their results are always in unicode. No cap.
Also those predeclared filters are based on subroutines that you can totally use by themselves (as XML::Twig::foo). Slay.
html_encode ($string)β usesHTML::Entitiesto encode a utf8 string πsafe_encode ($string)β uses either a regexp (perl < 5.8) orEncodeto encode non-ascii characters in the string in&#<nnnn>;formatsafe_encode_hex ($string)β uses either a regexp (perl < 5.8) orEncodeto encode non-ascii characters in the string in&#x<nnnn>;formatregexp2latin1 ($string)β uses a regexp to encode a utf8 string into latin 1 (ISO-8859-1). And heads up: does not work with Perl 5.8.0! π
output_text_filter
Same as output_filter, except it doesn't apply to the brackets and quotes around attribute values. This is the one for all the filters that could change the tagging β basically anything that does not just change the encoding of the output. html, safe and safe_hex are way better used with this option. π¦
input_filter
Similar to output_filter except the filter gets applied to the characters before they're stored in the twig, at parsing time. Vibes: catch it early.
remove_cdata
Setting this option to a true value will force the twig to output CDATA sections as regular (escaped) PCDATA. Iconic little glow-down, honestly.
parse_start_tag
If you use the 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 original_string() method) and returns a tag and the attributes in a hash (or in a list attribute_name/attribute value).
no_xxe
Prevents external entities from being 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 <!ENTITY xxe PUBLIC "bar" "/etc/passwd"> from making the password field available in the document. π Seriously, keep this on for anything you didn't write yourself.
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 print, sprint, flush and xml_string. Note that in the twig the entity will be stored as an element with a tag "#ENT" β 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 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: settingexpand_external_entsto0or-1currently doesn't work as expected; cf. <https://rt.cpan.org/Public/Bug/Display.html?id=118097>. To completely turn off expanding external entities useno_xxe.
no_xxe
If this argument is set to a true value, expanding of external entities is turned off. (Yep, you're seeing double β it shows up again here. Not me, that's just how the page is laid out π)
load_DTD
If this argument is set to a true value, parse or parsefile on the twig will load the DTD information. This information can then be accessed through the twig, in a 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 "DTD Handling" for more information. π
DTD_base <path_to_DTD_directory>
If the DTD is in a different directory, looks for it there β useful to make up somewhat for the lack of catalog suport in expat. You still need a SYSTEM declaration. (And yes, "suport" is exactly how it's spelled in the original, not me being chaotic for no reason π)
DTD_handler
Set a handler that will be called once the doctype (and the DTD) have been loaded, with 2 arguments: the twig and the DTD.
no_prolog
Does not output a prolog (XML declaration and DTD). Bye prolog bestie π
id
This optional argument gives the name of an attribute that can be used as an ID in the document. Elements whose ID is known can be accessed through the elt_id method. id defaults to 'id'. See "BUGS " πΈ
discard_spaces
If this optional argument is set to a true value then spaces are discarded when they look non-significant: strings containing only spaces and at least one line feed are discarded. This argument is set to true by default.
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.
discard_all_spaces
If this argument is set to a true value, spaces are discarded more aggressively than with discard_spaces: strings not including a \n are also dropped. This option is appropriate for data-oriented XML. It's giving "no time for your whitespace." π₯
keep_spaces
If this optional argument is set to a true value then all spaces in the document are kept, and stored as PCDATA.
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. Pick a lane π
discard_spaces_in
This argument sets keep_spaces to true but will cause 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']);
keep_spaces_in
This argument sets discard_spaces to true but will cause 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']);
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. (Same warning as above, it just applies here too π¦)
pretty_print
Set the pretty print method, amongst "none" (default), "nsgmls", "nice", "indented", "indented_c", "indented_a", "indented_close_tag", "cvs", "wrapped", "record" and "record_c".
pretty_print formats:
noneβ The document is output as one ling string, with no line breaks except those found within text elements. ("ling" β yes, that's a typo in the original, we keep it fr fr π)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 "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.
niceβ This option inserts line breaks before any tag that does not contain text (so elements with textual content are not broken, as the\nis the significant bit).
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! π
indentedβ Same as"nice"(and with the same warning) but indents elements according to their level.indented_cβ Same as"indented"but a little more compact: the closing tags are on the same line as the preceding text.indented_close_tagβ Same as"indented"except that the closing tag is also indented, to line up with the tags within the element. Very satisfying to look at, ngl β¨idented_aβ This formats XML files in a line-oriented version control friendly way. The format is described in <http://tinyurl.com/2kwscq> (that's an Oracle document with an insanely long URL). (And yes βidented_ais spelled that way right here in the page. Keeping it exactly as-is π)
β οΈ ok real talk first β the "spec" says attribute order shouldn't be messed with, so if your attributes aren't already in alphabetical order you're gonna need the keep_atts_order option. no cap.
cvsβ literally the same thing asidented_a. that's it, that's the whole vibe.wrappedβ same asindented_cexcept the lines get wrapped usingText::Wrap::wrap. the default line length is whatever$Text::Wrap::columnsdefaults to, and you can change it by changing that variable. slay.recordβ a record-oriented pretty print that shows data in records, one field per line (ngl it looks a LOT likeindented).record_cβ stands for record compact: one record per line. concise queen π
π empty_tags
Sets the display style for empty tags β pick "normal", "html" or "expand".
"normal"spits out an empty tag like"<tag/>"."html"adds a space, so"<tag />", for elements that can be empty in XHTML."expand"outputs"<tag></tag>".
π quote
Sets the quote character used for attributes β either "single" or "double".
π escape_gt
so by default XML::Twig does not escape the character > in its output, because the XML spec doesn't mandate it. flip this option on and > gets replaced by >. cute.
π comments
Sets how comments get processed: "drop" (the default), "keep" or "process".
Comments processing options, let's go:
dropβ drops the comments. they're not read, and not printed to the output. gone. ghosted. πkeepβ comments are loaded and will show up on the output, but they're not accessible within the twig and won't interfere with processing.
π Note: comments sitting in the middle of a text element, like this:
<p>text <!-- comment --> more text --></p>
get kept at their original position in the text."print"-style methods likesprintwill return the comments in the text.textorfieldon the other hand will NOT. and any use ofset_pcdataon the"#PCDATA"element (directly, or through other methods likeset_content) will delete the comment(s). rip.
processβ comments are loaded in the twig and treated as regular elements (their"tag"is"#COMMENT"). this can interfere with processing if you expect$elt->first_childto be an element but find a comment chillin' there instead. validation will NOT protect you from this, because comments can happen anywhere. use$elt->first_child( 'tag')(which is a good habit anyway, bestie) to get where you want. considerprocessif you're outputting SAX events from XML::Twig.
π pi
Sets how processing instructions get processed: "drop", "keep" (the default) or "process".
Note that you can also set PI handlers in the twig_handlers option:
'?' => \&handler
'?target' => \&handler 2
The handlers get called with 2 parameters β the twig and the PI element β if pi is set to process, and with 3 parameters β the twig, the target and the data β if pi is set to keep. obviously they won't be called at all if pi is set to drop.
If pi is set to keep, the handler should return a string that gets 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 there's no specific handler for that target available.
π map_xmlns
You pass this option a hashref that maps uri's to prefixes. the prefixes in the document get replaced by the ones in the map. the mapped prefixes can (actually have to) be used to trigger handlers, navigate or query the document. ok ikyk.
here's 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;
which outputs this:
<doc xmlns:svg="http://www.w3.org/2000/svg">
<svg:circle cx="10" cy="90" r="20"/>
</doc>
π keep_original_prefix
when used with map_xmlns, this option makes XML::Twig use the original namespace prefixes when outputting a document. the mapped prefix still gets used for triggering handlers, and in navigation and query methods. best of both worlds fr.
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;
which outputs:
<doc xmlns:gr="http://www.w3.org/2000/svg">
<gr:circle cx="10" cy="90" r="20"/>
</doc>
π original_uri ($prefix)
called from within a handler, this returns the uri bound to the namespace prefix in the original document. iconic.
π index ($arrayref or $hashref)
this option creates lists of specific elements while the XML is being parsed. you hand it a reference to either a list of triggering expressions, or to a hash of name => expression, and for each one it generates the list of elements matching that expression. you can get at the list through the index method. π
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);
β οΈ heads up: the index is not maintained after parsing. if elements get deleted, renamed or otherwise hurt during processing, the index is NOT updated. (changing the id element OTOH will update the index.) don't say i didn't warn you π
π att_accessors <list of attribute names>
creates methods that give you direct access to an attribute:
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
π elt_accessors
creates methods that give you direct access to the first child element (in scalar context) or the list of elements (in list context).
you can give the list of accessors to create in 1 of 2 ways: in an array, or in a hash of 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]')
π field_accessors
creates methods that give you direct access to the first child element's text. so convenient honestly:
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');
π use_tidy
set this option to use HTML::Tidy instead of HTML::TreeBuilder to convert HTML to XML. HTML β especially real (like, real "crap") HTML found out there in the wild β hmm, the sentence trails off in the original, but the point is: depending on the data, one module or the other does a better job at the conversion. also HTML::Tidy can be a bit difficult to install, so XML::Twig offers you both options. TIMTOWTDI, periodt. π
π output_html_doctype
when you're using HTML::TreeBuilder to convert HTML, this option causes the DOCTYPE declaration to be output, which may be important for some legacy browsers. without that option, the DOCTYPE definition is NOT output. also, if the definition is completely wrong (ie not easily parsable), it's not output either. π
π«Ά Note from the author, and honestly iconic behavior: I HATE the Java-like name of arguments used by most XML modules. So in pure TIMTOWTDI fashion, all arguments can be written either asUglyJavaLikeNameor asreadable_perl_name:twig_print_outside_rootsorTwigPrintOutsideRoots(or eventwigPrintOutsideRoots{shudder}). XML::Twig normalizes them before processing them. so write it however your little heart desires β¨
π§ parse ( $source)
The $source parameter should either be a string containing the whole XML document, or it should be an open IO::Handle (aka a filehandle). either way, she's ready.
π if a parse error happens, adiecall gets thrown. otherwise it returns the twig built by the parse. usesafe_parseif you want the parsing to return even when an error occurs β much more chill.
If this method is called as a class method (XML::Twig->parse( $some_xml_or_html)) then an XML::Twig object gets 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. main character energy tbh π
Quick vibe check before the next batch of methods, bestie π β when you're parsing a filehandle, do NOT open it with an encoding. Like literally open it plain:open( my $in, '<', $filename). The file gets parsed byexpat, 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 useparsefileon the file name, instead of<parse>on the open file. π«Ά
parsestring
This is literally just an alias for parse, kept around for backwards compatibility. π
parsefile (FILE [, OPT => OPT_VALUE [...]])
Opens FILE for reading, then calls parse with the open handle. The file is closed no matter how parse returns. If a parse error happens it throws a die call; otherwise it returns the twig built by the parse. Want parsing to come back even when an error occurs? Use safe_parsefile. β¨
parsefile_inplace ( $file, $optional_extension)
Parses and updates a file in place. The way it does this: it creates a temp file, selects that temp file as the default for print() statements (and methods), then parses the input file. If parsing succeeds, the temp file is moved to replace the input file. If you pass an extension, the original file gets backed up (the rules for the extension are the same as the rules for the -i option in perl). π
parsefile_html_inplace ( $file, $optional_extension)
Same as parsefile_inplace, except it parses HTML instead of XML. π¦
parseurl ($url $optional_user_agent)
Gets the data from $url and parses it. The data is piped to the parser in chunks the size of the XML::Parser::Expat buffer, so memory consumption and hopefully speed are optimal. 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. π«
safe_parse (SOURCE [, OPT => OPT_VALUE [...]])
This method is similar to parse except that it wraps the parsing in an eval block. It returns the twig on success and 0 on failure (the twig object also contains the parsed twig). $@ contains the error message on failure. π
Note that the parsing still stops as soon as an error is detected β there is no way to keep going after an error. Periodt.
safe_parsefile (FILE [, OPT => OPT_VALUE [...]])
This method is similar to parsefile except that it wraps the parsing in an eval block. It returns the twig on success and 0 on failure (the twig object also contains the parsed twig). $@ contains the error message on failure.
Note that the parsing still stops as soon as an error is detected β there is no way to keep going after an error. Fr fr.
safe_parseurl ($url $optional_user_agent)
Same as parseurl except that it wraps the parsing in an eval block. It returns the twig on success and 0 on failure (the twig object also contains the parsed twig). $@ contains the error message on failure. π«Ά
parse_html ($string_or_fh)
Parses an HTML string or file handle (by converting it to XML using HTML::TreeBuilder, which needs to be available).
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 ]]> --> ). π
parsefile_html ($file)
Parses an HTML file (by converting it to XML using HTML::TreeBuilder, which needs to be available, or HTML::Tidy if the use_tidy option was used). The file is loaded completely in memory and converted to XML before being parsed.
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. π
parseurl_html ($url $optional_user_agent)
Parses an URL as html the same way parse_html does. π¦
safe_parseurl_html ($url $optional_user_agent)
Same as parseurl_html except that it wraps the parsing in an eval block. It returns the twig on success and 0 on failure (the twig object also contains the parsed twig). $@ contains the error message on failure. β¨
safe_parsefile_html ($file $optional_user_agent)
Same as parsefile_html except that it wraps the parsing in an eval block. It returns the twig on success and 0 on failure (the twig object also contains the parsed twig). $@ contains the error message on failure. π
safe_parse_html ($string_or_fh)
Same as parse_html except that it wraps the parsing in an eval block. It returns the twig on success and 0 on failure (the twig object also contains the parsed twig). $@ contains the error message on failure. π
xparse ($thing_to_parse)
Parses the $thing_to_parse, whether it is a filehandle, a string, an HTML file, an HTML URL, an URL or a file. π
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. Ngl.
nparse ($optional_twig_options, $thing_to_parse)
Creates a twig with the $optional_options, and parses the $thing_to_parse, whether it is a filehandle, a string, an HTML file, an HTML URL, an URL or a file. π
Examples:
XML::Twig->nparse( "file.xml");
XML::Twig->nparse( error_context => 1, "file://file.xml");
nparse_pp ($optional_twig_options, $thing_to_parse)
Same as nparse but also sets the pretty_print option to indented. π
nparse_e ($optional_twig_options, $thing_to_parse)
Same as nparse but also sets the error_context option to 1. π₯
nparse_ppe ($optional_twig_options, $thing_to_parse)
Same as nparse but also sets the pretty_print option to indented and the error_context option to 1. π
parser
This method returns the expat object (actually the XML::Parser::Expat object) used during parsing. It is useful for example to call XML::Parser::Expat methods on it. To get the line of a tag for example use $t->parser->current_line. π§
setTwigHandlers ($handlers)
Sets the twig_handlers. $handlers is a reference to a hash similar to the one in the twig_handlers option of new. All previous handlers are unset. The method returns the reference to the previous handlers. π
setTwigHandler ($exp $handler)
Sets a single twig_handler for elements matching $exp. $handler is a reference to a subroutine. If the handler was previously set then the reference to the previous handler is returned. β¨
setStartTagHandlers ($handlers)
Sets the start_tag handlers. $handlers is a reference to a hash similar to the one in the start_tag_handlers option of new. All previous handlers are unset. The method returns the reference to the previous handlers. π
setStartTagHandler ($exp $handler)
Sets a single start_tag handlers for elements matching $exp. $handler is a reference to a subroutine. If the handler was previously set then the reference to the previous handler is returned. π¦
setEndTagHandlers ($handlers)
Sets the end_tag handlers. $handlers is a reference to a hash similar to the one in the end_tag_handlers option of new. All previous handlers are unset. The method returns the reference to the previous handlers. πΈ
setEndTagHandler ($exp $handler)
Sets a single end_tag handlers for elements matching $exp. $handler is a reference to a subroutine. If the handler was previously set then the reference to the previous handler is returned. π
setTwigRoots ($handlers)
Same as using the twig_roots option when creating the twig. π
setCharHandler ($exp $handler)
Sets a char_handler. β
setIgnoreEltsHandler ($exp)
Sets an ignore_elt handler (elements that match $exp will be ignored). π
setIgnoreEltsHandlers ($exp)
Sets all ignore_elt handlers (previous handlers are replaced). π«
dtd
Returns the dtd (an XML::Twig::DTD object) of a twig. π
xmldecl
Returns the XML declaration for the document, or a default one if it doesn't have one. β¨
doctype
Returns the doctype for the document. π¦
doctype_name
Returns the doctype of the document from the doctype declaration. πΈ
system_id
Returns the system value of the DTD of the document from the doctype declaration. π
public_id
Returns the public doctype of the document from the doctype declaration. π
internal_subset
Returns the internal subset of the DTD. π
dtd_text
Returns the DTD text. β
dtd_print
Prints the DTD. π¨οΈ
model ($tag)
Returns the model (in the DTD) for the element $tag. π§
root
Returns the root element of a twig. π³
set_root ($elt)
Sets the root of a twig. π
first_elt ($optional_condition)
Returns the first element matching $optional_condition of a twig; if no condition is given then the root is returned. π₯
last_elt ($optional_condition)
Returns the last element matching $optional_condition of a twig; if no condition is given then the last element of the twig is returned. π«
elt_id ($id)
Returns the element whose id attribute is $id. π
getEltById
Same as elt_id. β¨
index ($index_name, $optional_index)
If the $optional_index argument is present, returns the corresponding element in the index (created using the index option for XML::Twig->new).
If the argument is not present, returns an arrayref to the index. πΈ
normalize
Merges together all consecutive pcdata elements in the document (if for example you have turned some elements into pcdata using erase, this will give you a "clean" document in which all the text elements are as long as possible). π
encoding
This method returns the encoding of the XML document, as defined by the encoding attribute in the XML declaration (ie it is undef if the attribute is not defined). π¦
set_encoding
This method sets the value of the encoding attribute in the XML declaration. Note that if the document did not have a declaration it is generated (with an XML version of 1.0). π
xml_versionβ hands you the XML version, like, the actualversionattribute from the XML declaration. If that attribute's not defined? You getundef. Sorry bestie, that's the vibe check result πset_xml_versionβ sets theversionattribute on the XML declaration. And if there was no declaration at all? It makes one. Iconic, self-starting behavior β¨set_standaloneβ sets the value of thestandaloneattribute in the XML declaration. Heads up tho: if the document had no declaration, one gets generated for it (with an XML version of 1.0, no cap) πstandaloneβ returns the value of thestandalonedeclaration for the document π¦set_output_encodingβ sets the "encoding" "attribute" in the XML declaration. (Yes, the original really does put "attribute" in quotes like that, we're keeping it π)set_doctype ($name, $system, $public, $internal)β sets the doctype of the element. The rules, bestie, listen closely:- if an argument is
undef(or just not passed at all) β its old value is kept π«Ά - if you pass a false value (
''or0) β the old value gets deleted π
- if an argument is
entity_listβ returns the entity list of a twig πΈentity_namesβ returns the list of all defined entities πentity ($entity_name)β returns the entity with that name πnotation_listβ returns the notation list of a twig πnotation_namesβ returns the list of all defined notations βnotation ($notation_name)β returns the notation πchange_gi ($old_gi, $new_gi)β does a (very fast!) global change: every$old_gielement is now$new_gi. Sounds slay but it's a bit dangerous, and you should avoid it if possible, because the new tag might get ignored in subsequent processing π
See "BUGS" for the receipts.
flush ($optional_filehandle, %options)β flushes a twig up to (and including) the current element, then deletes all the unnecessary elements from the tree it's keeping in memory. The wayflushkeeps track of which elements need to be open/closed means if you flush from handlers you literally don't have to worry about anything π§ Just keep flushing the twig every time you're done with a sub-tree and it'll come out well-formed, periodt. After the whole parsing, don't forget toflushone more time to print the end of the document. The doctype and entity declarations get printed too π
flush takes an optional filehandle as an argument.
If you use flush at any point during parsing, the document gets flushed one last time at the end of the parsing, to the proper filehandle.
options: use the update_DTD option if you've 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);
flush_up_to ($elt, $optional_filehandle, %options)β flushes up to the$eltelement. This is how you keep part of the tree in memory while youflushπ¦
options: see flush.
purgeβ does the same asflushexcept it does not print the twig. It just deletes all elements that have been completely parsed so far πpurge_up_to ($elt)β purges up to the$eltelement. Again: keeps part of the tree in memory while youpurgeβ¨print ($optional_filehandle, %options)β prints the whole document associated with the twig. Use it only AFTER the parse, bestie, not during π₯
options: see flush.
print_to_file ($filename, %options)β prints the whole document associated with the twig to the file$filename. Only AFTER the parse π
options: see flush.
safe_print_to_file ($filename, %options)β prints the whole document associated with the twig to the file$filename. This variant, which probably only works on *nix, prints to a temp file, then moves the temp file to overwrite the original file π
It's a bit safer when 2 processes could potentially write the same file: only the last one will succeed, but the file won't be corrupted. The author literally says he often uses this for cron jobs, so testing the code doesn't interfere with the cron job running at the same time π
options: see flush.
sprintβ returns the text of the whole document associated with the twig. Only AFTER the parse πΈ
options: see flush.
trimβ trims the document: gets rid of initial and trailing spaces, and replaces multiple spaces by a single one β¨toSAX1 ($handler)β sends SAX events for the twig to the SAX1 handler$handlerπ¦toSAX2 ($handler)β sends SAX events for the twig to the SAX2 handler$handlerπ¦flush_toSAX1 ($handler)β same as flush, except the SAX events go to the SAX1 handler$handlerinstead of the twig being printed πflush_toSAX2 ($handler)β same as flush, except the SAX events go to the SAX2 handler$handlerinstead of the twig being printed πignoreβ call this one during parsing, usually insidestart_tag_handlers. It makes the element get skipped during parsing: the twig isn't built for it, and it won't be accessible during parsing or after it. The element takes up zero memory and parsing goes faster β main character efficiency π
Note that you can also call this method on an element. If that element is a parent of the current element, then this element gets ignored (the twig stops being built for it, and whatever was already built gets deleted) π
set_pretty_print ($style)β sets the pretty print method, among"none"(default),"nsgmls","nice","indented",indented_c,"wrapped","record"and"record_c"β¨
WARNING: the pretty print style is a GLOBAL variable, so once it's set it applies to ALLsprint's). Same deal if you use XML::Twig withmod_perl. Shouldn't be a problem tho, since the XML that gets generated is valid anyway, and XML processors (as well as HTML processors, including browsers) shouldn't care. Let the author know if this is a big problem, but at the moment the performance/cleanliness trade-off clearly favors the global approach π«Ά
set_empty_tag_style ($style)β sets the empty tag display style ("normal","html"or"expand"). Likeset_pretty_print, this sets a global flag π"normal"outputs an empty tag"<tag/>""html"adds a space,"<tag />", for elements that can be empty in XHTML"expand"outputs"<tag></tag>"
set_remove_cdata ($flag)β sets (or unsets) the flag that forces the twig to output CDATA sections as regular (escaped) PCDATA πprint_prolog ($optional_filehandle, %options)β prints the prolog (XML declaration + DTD + entity declarations) of a document β
options: see flush.
prolog ($optional_filehandle, %options)β returns the prolog (XML declaration + DTD + entity declarations) of a document π¦
options: see flush.
finishβ calls Expat'sfinishmethod. Unsets all handlers (including the internal ones that set context), but expat keeps parsing to the end of the document or until it finds an error. It should finish up a lot faster than with the handlers set π₯finish_printβ stops twig processing, flushes the twig and proceeds to finish printing the document as fast as possible. Use this one when you're modifying a document and the modification is done πfinish_nowβ stops twig processing and does not finish parsing the document (which could actually be not well-formed after the point wherefinish_nowis called π). Execution resumes after theparseorparsefilecall. The content of the twig is what's been parsed so far (all open elements at the timefinish_nowis called are considered closed) πset_expand_external_entitiesβ same as using theexpand_external_entsoption when creating the twig πΈset_input_filterβ same as using theinput_filteroption when creating the twig πΈset_keep_atts_orderβ same as using thekeep_atts_orderoption when creating the twig πΈset_keep_encodingβ same as using thekeep_encodingoption when creating the twig πΈescape_gtβ usually XML::Twig doesn't escape>in its output. Using this option makes it replace>by>β¨do_not_escape_gtβ reverts XML::Twig behavior to its default of not escaping>in its output πset_output_filterβ same as using theoutput_filteroption when creating the twig πset_output_text_filterβ same as using theoutput_text_filteroption when creating the twig πactive_twigβ a class method that returns the last processed twig, so you don't necessarily need the object to call methods on it π (iykyk, that's convenient)add_stylesheet ($type, @options)β adds an external stylesheet to an XML document π¨
Supported types and options:
xsl β option: the url of the stylesheet.
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"?>
css β option: the url of the stylesheet.
Methods inherited from XML::Parser::Expat π
A twig inherits all the relevant methods from XML::Parser::Expat. But bestie, these methods can only be used during the parsing phase β otherwise they generate a fatal error π (so, no, not after, not later, only during.)
Inherited methods are:
depthβ returns the size of the context list πin_elementβ returns true if NAME is equal to the name of the innermost currently opened element. If namespace processing is being used and you want to check against a name that may be in a namespace, then use thegenerate_ns_namemethod to create the NAME argument β¨within_elementβ returns the number of times the given name appears in the context list. If namespace processing is being used and you want to check against a name that may be in a namespace, then use thegenerate_ns_namemethod to create the NAME argument π¦contextβ returns a list of element names that represent open elements, with the last one being the innermost. Inside start and end tag handlers, this will be the tag of the parent element πcurrent_lineβ returns the line number of the current position of the parse πcurrent_columnβ returns the column number of the current position of the parse πcurrent_byteβ returns the current position of the parse πposition_in_contextβ Returns a string that shows the current parse position.LINESshould be an integer>= 0that represents the number of lines on either side of the current parse line to place into the returned string. πbase ([NEWBASE])β Returns the current value of the base for resolving relative URIs. IfNEWBASEis supplied, changes the base to that value. β¨current_elementβ Returns the name of the innermost currently opened element. Inside start or end handlers, returns the parent of the element associated with those tags.element_indexβ Returns an integer that is the depth-first visit order of the current element. This will be zero outside of the root element. For example, this will return1when called from the start handler for the root element start tag. πrecognized_stringβ Returns the string from the document that was recognized in order to call the current handler. For instance, when called from a start handler, it will give us the start-tag string. The string is encoded in UTF-8. This method doesnβt return a meaningful string inside declaration handlers.original_stringβ Returns the verbatim string from the document that was recognized in order to call the current handler. The string is in the original document encoding. This method doesnβt return a meaningful string inside declaration handlers. π¦xpcroakβ Concatenate onto the given message the current line number within the XML document plus the message implied byErrorContext. Then croak with the formed message.xpcarpβ Concatenate onto the given message the current line number within the XML document plus the message implied byErrorContext. Then carp with the formed message.xml_escape(TEXT [, CHAR [, CHAR ...]])β ReturnsTEXTwith markup characters turned into character entities. Any additional characters provided as arguments are also turned into character references where found inTEXT.
Heads up: this method is broken on some versions of expat/XML::Parser. π
path ( $optional_tag)β Return the element context in a form similar to XPathβs short form:'"/root/tag1/../tag"'. πΈget_xpath ( $optional_array_ref, $xpath, $optional_offset)β Performs aget_xpathon the document root (see "Elt").
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.
find_nodes ( $optional_array_ref, $xpath, $optional_offset)β same asget_xpath.findnodes ( $optional_array_ref, $xpath, $optional_offset)β same asget_xpath(similar to the XML::LibXML method).findvalue ( $optional_array_ref, $xpath, $optional_offset)β Return thejoinof all texts of the results of applyingget_xpathto the node (similar to the XML::LibXML method).findvalues ( $optional_array_ref, $xpath, $optional_offset)β Return an array of all texts of the results of applyingget_xpathto the node.subs_text ($regexp, $replace)βsubs_textdoes text substitution on the whole document, similar to perlβss///operator. πdisposeβ Useful only if you donβt haveScalar::UtilorWeakRefinstalled.
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.
att_accessors (list_of_attribute_names)β A convenience method that creates l-valued accessors for attributes. So$twig->create_accessors( 'foo')will create afoomethod that can be called on elements:
$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).
create_accessors (list_of_attribute_names)β Same asatt_accessors.elt_accessors (list_of_attribute_names)β A convenience method that creates accessors for elements. So$twig->create_accessors( 'foo')will create afoomethod that can be called on elements:
$elt->foo; # equivalent to $elt->first_child( 'foo');
field_accessors (list_of_attribute_names)β A convenience method that creates accessors for element values (field). So$twig->create_accessors( 'foo')will create afoomethod that can be called on elements:
$elt->foo; # equivalent to $elt->field( 'foo');
set_do_not_escape_amp_in_attsβ An evil method, that I only document becauseTest::Pod::Coveragecomplaints otherwise, but really, you donβt want to know about it. π
π XML::Twig::Elt π
new ($optional_tag, $optional_atts, @optional_content)β Thetagis optional (but then you canβt have a content ), the$optional_attsargument is a reference to a hash of attributes, the content can be just a string or a list of strings and element. A content of"#EMPTY"creates an empty element;
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]]></>
parse ($string, %args)β Creates an element from an XML string. The string is actually parsed as a new twig, then the root of that twig is returned. The arguments in%argsare passed to the twig. As always if the parse fails the parser will die, so use anevalif you want to trap syntax errors.
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>");
set_inner_xml ($string)β Sets the content of the element to be the tree created from the string. π§set_inner_html ($string)β Sets the content of the element, after parsing the string with an HTML parser (HTML::Parser).set_outer_xml ($string)β Replaces the element with the tree created from the string.print ($optional_filehandle, $optional_pretty_print_style)β Prints an entire element, including the tags, optionally to a$optional_filehandle, optionally with a$pretty_print_style.
The print outputs XML data so base entities are escaped.
print_to_file ($filename, %options)β Prints the element to file$filename.
options: see "flush".
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$eltare not). The text is XML-escaped: base entities (&and<in text,&<and"in attribute values) are turned into entities. πgiβ Return the gi of the element (the gi is the "generic identifier" the tag name in SGML parlance).
tag and name are synonyms of gi.
tagβ Same asgi.nameβ Same astag.set_gi ($tag)β Set the gi (tag) of an element.set_tag ($tag)β Set the tag (="tag") of an element.set_name ($name)β Set the name (="tag") of an element.rootβ Return the root of the twig in which the element is contained.twigβ Return the twig containing the element. π«Άparent ($optional_condition)β Return the parent of the element, or the first ancestor matching the$optional_condition.first_child ($optional_condition)β Return the first child of the element, or the first child matching the$optional_condition.has_child ($optional_condition)β Return the first child of the element, or the first child matching the$optional_condition(same asfirst_child).has_children ($optional_condition)β Return the first child of the element, or the first child matching the$optional_condition(same asfirst_child).first_child_text ($optional_condition)β Return the text of the first child of the element, or the first child matching the$optional_conditionIf there is nofirst_childthen returns''. This avoids getting the child, checking for its existence then getting the text for trivial cases. π
Similar methods are available for the other navigation methods:
last_child_textprev_sibling_textnext_sibling_textprev_elt_textnext_elt_textchild_textparent_text
All this methods also exist in "trimmed" variant:
first_child_trimmed_textlast_child_trimmed_textprev_sibling_trimmed_textnext_sibling_trimmed_textprev_elt_trimmed_textnext_elt_trimmed_textchild_trimmed_textparent_trimmed_text
field ($condition)β Same method asfirst_child_textwith a different name.fields ($condition_list)β Return the list of field (text of first child matching the conditions), missing fields are returned as the empty string.
Same method as first_child_text with a different name. π
trimmed_field ($optional_condition)
okay so this is literally the exact same method as first_child_trimmed_text, just with a different name β¨ same vibes, different label, iykyk.
set_field ($condition, $optional_atts, @list_of_elt_and_strings)
This one sets the content of the first child of the element that matches $condition π
β and the rest of the arguments work exactly like they do for set_content.
Here's the cute part: if no child matches $condition, and $condition happens to be a valid XML element name, then a whole new element with that name gets created and pasted in as the last child π
first_child_matches ($optional_condition)
Returns the element if the first child of the element (assuming it even exists) passes the $optional_condition β otherwise undef, no cap π
So this:
if( $elt->first_child_matches( 'title')) ...
is literally equivalent to:
if( $elt->first_child && $elt->first_child->passes( 'title'))
first_child_is is just another name for this same method, bestie π«Ά
And the similar methods exist for all the other navigation methods too β here's the whole squad:
last_child_matchesprev_sibling_matchesnext_sibling_matchesprev_elt_matchesnext_elt_matcheschild_matchesparent_matches
is_first_child ($optional_condition)
returns true (the element itself) if the element is the first child of its parent β optionally that satisfies the $optional_condition π
is_last_child ($optional_condition)
same deal but the other end: returns true (the element) if it's the last child of its parent, optionally satisfying the $optional_condition β¨
prev_sibling ($optional_condition)
Return the previous sibling of the element β or the previous sibling matching $optional_condition π¦
next_sibling ($optional_condition)
Return the next sibling of the element β or the first one matching $optional_condition.
next_elt ($optional_elt, $optional_condition)
Return the next elt of the element (optionally matching $optional_condition) π
Quick definition so you're not confused: "next elt" = the next element which opens after the current element opens. Which usually means the first child of the element. Counter-intuitive as it might look, this is exactly what lets you loop through the whole document by starting from the root π
The $optional_elt is the root of a subtree. When the next_elt ends up out of the subtree, the method returns undef. So you can walk a sub-tree like this:
my $elt= $subtree_root;
while( $elt= $elt->next_elt( $subtree_root))
{ # insert processing code here
}
prev_elt ($optional_condition)
Return the previous elt (optionally matching $optional_condition) of the element. This is the first element which opens before the current one. It's usually either the last descendant of the previous sibling or simply the parent π
next_n_elt ($offset, $optional_condition)
Return the $offset-th element that matches the $optional_condition π―
following_elt
Return the following element (as per the XPath following axis) β
preceding_elt
Return the preceding element (as per the XPath preceding axis) β
following_elts
Return the list of following elements (as per the XPath following axis) π¦
preceding_elts
Return the list of preceding elements (as per the XPath preceding axis) π¦
children ($optional_condition)
Return the list of children of the element (optionally only the ones matching $optional_condition). The list comes in document order, always π
children_count ($optional_condition)
Return the number of children of the element (optionally only the ones matching $optional_condition) π’
children_text ($optional_condition)
In array context: returns an array containing the text of the children of the element (optionally matching $optional_condition).
In scalar context: returns the concatenation of the text of the children of the element π§
children_trimmed_text ($optional_condition)
In array context: returns an array with the trimmed text of the children of the element (optionally matching $optional_condition).
In scalar context: returns the concatenation of the trimmed text of the children of the element β¨
children_copy ($optional_condition)
Return a list of elements that are copies of the children of the element, optionally only the ones matching $optional_condition π
descendants ($optional_condition)
Return the list of all descendants of the element (optionally matching $optional_condition). This is the equivalent of the getElementsByTagName of the DOM β and btw, if you're really a DOM addict, you can just use getElementsByTagName instead π
getElementsByTagName ($optional_condition)
Same as descendants π«
find_by_tag_name ($optional_condition)
Also same as descendants π«
descendants_or_self ($optional_condition)
Same as descendants except the element itself gets included in the list if it matches the $optional_condition π«Ά
first_descendant ($optional_condition)
Return the first descendant of the element that matches the condition π₯
last_descendant ($optional_condition)
Return the last descendant of the element that matches the condition π
ancestors ($optional_condition)
Return the list of ancestors of the element (optionally matching $optional_condition). The list is ordered from the innermost ancestor to the outermost one π
NOTE: the element itself is not part of the list β if you want it in there you're gonna have to use ancestors_or_self π
ancestors_or_self ($optional_condition)
Return the list of ancestors of the element (optionally matching $optional_condition), including the element itself (if it matches the condition). The list is ordered from the innermost ancestor to the outermost one β¨
passes ($condition)
Return the element if it passes the $condition π
att ($att)
Return the value of attribute $att, or undef if it's not there.
latt ($att)
Return the value of attribute $att, or undef.
This method is an lvalue, so you can literally do this:
$elt->latt( 'foo')= 'bar'
or even:
$elt->latt( 'foo')++;
obsessed honestly π₯
set_att ($att, $att_value)
Set the attribute of the element to the given value.
And plot twist, you can set several attributes at once like this:
$elt->set_att( att1 => "val1", att2 => "val2");
del_att ($att)
Delete the attribute for the element.
You can delete several attributes at once too:
$elt->del_att( 'att1', 'att2', 'att3');
att_exists ($att)
Returns true if the attribute $att exists for the element, false otherwise π―
cut
Cut the element from the tree. The element still exists (!!), it can be copied or pasted somewhere else β it's just not attached to the tree anymore π
heads up: the "old" links to the parent, previous and next siblings can still be accessed using the former_* methods π
former_next_sibling
Returns the former next sibling of a cut node (or undef if the node has not been cut).
This makes it way easier to write loops where you cut elements:
my $child= $parent->first_child( 'achild');
while( $child->att( 'cut'))
{ $child->cut; $child= $child->former_next_sibling; }
former_prev_sibling
Returns the former previous sibling of a cut node (or undef if the node has not been cut).
former_parent
Returns the former parent of a cut node (or undef if the node has not been cut).
cut_children ($optional_condition)
Cut all the children of the element (or all of the ones that satisfy the $optional_condition) βοΈ
Return the list of children.
cut_descendants ($optional_condition)
Cut all the descendants of the element (or all of the ones that satisfy the $optional_condition) βοΈ
Return the list of descendants.
copy ($elt)
Return a copy of the element. The copy is a "deep" copy: all sub-elements of the element are duplicated πͺ
paste ($optional_position, $ref)
Paste a previously cut (or freshly generated) element. It will die if the element already belongs to a tree π
So real talk β the calling element is what gets 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 time π
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:
first_child(default) β The element is pasted as the first child of$reflast_childβ The element is pasted as the last child of$refbeforeβ The element is pasted before$ref, as its previous sibling.afterβ The element is pasted after$ref, as its next sibling.withinβ In this case an extra argument,$offset, should be supplied. The element will be pasted in the reference element (or in its first text child) at the given offset. To achieve this the reference element will be split at the offset β¨
And btw, you can call the underlying method directly too:
paste_beforepaste_afterpaste_first_childpaste_last_childpaste_within
move ($optional_position, $ref)
Move an element in the tree. This is literally just a cut and then a paste. The syntax is the same as paste π
replace ($ref)
Replaces an element in the tree. Sometimes it's just not possible to cut an element and then paste another in its place, so replace comes in handy. The calling element replaces $ref π
replace_with (@elts)
Replaces the calling element with one or more elements π¦
delete
Cut the element and frees the memory π
prefix ($text, $optional_option)
Add a prefix to an element. Here's how it works, bestie:
- if the element is a
PCDATAelement, the text is added to the pcdata π - if the element's first child is a
PCDATA, then the text is added to its pcdata - otherwise a new
PCDATAelement is created and pasted as the first child of the element β¨
If the option is asis, then the prefix is added as-is: it's 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 π
π suffix ($text, $optional_option)
Okay so this one tacks a little something onto the end of an element π. If the element is a PCDATA element, the text just gets added onto the pcdata. If the element's last child is a PCDATA, the text gets added to that kid's pcdata. Otherwise, bestie, a brand new PCDATA element gets created and pasted in as the last child of the element. Slay.
If the option is asis then the suffix is added as-is: it's created in a separate PCDATA element with an asis property. So then you can write stuff like:
$elt2->suffix( '</b>', 'asis');
β¨ trim
Trims the element in place β spaces at the beginning and at the end of the element get discarded, and multiple spaces within the element (or its descendants) get squished into a single space π«§.
Heads up though: in some cases you can still end up with multiple spaces, if they're split between several elements:
<doc> text <b> hah! </b> yep</doc>
gets trimmed to
<doc>text <b> hah! </b> yep</doc>
And the docs literally say: "This is somewhere in between a bug and a feature." π iconic honestly.
normalize
Merges together all consecutive pcdata elements in the element. So if, for example, you turned some elements into pcdata using erase, this gives you a "clean" element where all the text fragments are as long as possible π
.
simplify (%options)
Returns a data structure suspiciously similar to XML::Simple's π. The options are identical to XMLin options, so see the XML::Simple doc for more details (or just use DATA::dumper or YAML to dump the data structure).
Note: there is no magic here β if you write $twig->parsefile( $file )->simplify(); then it will load the entire document in memory. Yeah, sorry, you're gonna 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.
The options are:
content_keyforcearraykeyattrnoattrnormalize_spaceβ akanormalise_spacevariables(%var_hash)var_att($attribute_name)var_regexp(regexp)group_tags{ grouping tag => grouped tag, grouping tag 2 => grouped tag 2...}
π¦ variables (%var_hash)
%var_hash is a hash { name => value } π.
This option lets variables in the XML get expanded when the file is read. (And nope β there's no facility for putting the variable names back if you regenerate XML using XMLout, so, like, fair warning π.)
A 'variable' is any text of the form ${name} (or $name) that occurs in an attribute value or in the text content of an element. If 'name' matches a key in the supplied hashref, ${name} gets replaced with the corresponding value from the hashref. If no matching key is found, the variable is just... not replaced. Left hanging. π
πΈ var_att ($attribute_name)
This option gives the name of an attribute that'll be used to create variables in the XML:
<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+)/
β var_regexp (regexp)
This option changes the regexp used to capture variables. The variable name should be in $1 π―.
π group_tags { grouping tag => grouped tag, grouping tag 2 => grouped tag 2...}
Option used to simplify the structure: the elements you list will not be used. Their children will be β they get considered children of the element parent π§.
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'
π split_at ($offset)
Splits a text (PCDATA or CDATA) element into 2 at $offset. The original element now holds the first part of the string, and a new element holds the right part. The new element is what gets returned π.
If the element is not a text element, then the first text child of the element gets split instead.
β¨ split ( $optional_regexp, $tag1, $atts1, $tag2, $atts2...)
Splits the text descendants of an element in place. The text gets split using $regexp, and if the regexp includes () then the matched separators get wrapped in elements π. $1 gets wrapped in $tag1, with attributes $atts1 if $atts1 is given (as a hashref), $2 gets wrapped in $tag2...
So 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), and it defaults to \s+ just like the split built-in β but, like, that'd be a pretty useless behaviour without the $optional_tag parameter, ngl π.
$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) π.
π
mark ( $regexp, $optional_tag, $optional_attribute_ref)
This method behaves exactly as split, except only the newly created elements are returned. Same energy, tidier output β¨.
π¦ wrap_children ( $regexp_string, $tag, $optional_attribute_hashref)
Wraps the children of the element that match the regexp in an element $tag π. If $optional_attribute_hashref is passed, then the new element gets these attributes.
$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: elements might get extraidattributes in the process. Seeadd_id. Usestrip_attto remove unwanted id's.
Here's 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>
πΈ subs_text ($regexp, $replace)
subs_text does text substitution, similar to perl's s/// operator βοΈ.
$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 elements and entities, by using &elt( tag => { att => val }, text) (similar syntax as new) and &ent( name) π«.
Here's 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: the substitution is always global, as in using the g modifier in a perl substitution, and it's 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. e.g.$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...
π add_id ($optional_coderef)
Adds an id to the element π·οΈ.
The id is an attribute, id by default β see the id option for XML::Twig new to change it. And here's a cute trick: use an id starting with # to get an id that's not output by print, flush or sprint, yet that lets you use the elt_id method to get the element easily πβ¨.
okay so picking up mid-add_id (no dramatic re-intro, weβre already in the group chat): if the element already has an id, no new id is generated. By default the method creates an id of the form twig_id_<nnnn>, where <nnnn> is a number, incremented each time the method is called successfully.
π set_id_seed ($prefix)
By default the id generated by add_id is twig_id_<nnnn>. set_id_seed changes the prefix to $prefix and resets the number to 1.
π¦ strip_att ($att)
Remove the attribute $att from all descendants of the element (including the element itself).
Return the element.
πΈ change_att_name ($old_name, $new_name)
Change the name of the attribute from $old_name to $new_name. If there is no attribute $old_name, nothing happens.
π lc_attnames
Lowercases the names of all the attributes of the element.
β¨ sort_children_on_value( %options)
Sort the children of the element in place according to their text. All children are sorted.
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. (Yes bestie, it says that twice: return the element, with its children sorted.)
π«Ά sort_children_on_att ($att, %options)
Sort the children of the element in place according to attribute $att. %options are the same as for sort_children_on_value.
Return the element.
π sort_children_on_field ($tag, %options)
Sort the children of the element in place, according to the field $tag (the text of the first child of the child with this tag). %options are the same as for sort_children_on_value.
Return the element, with its children sorted.
π
sort_children( $get_key, %options)
Sort the children of the element in place. The $get_key argument is a reference to a function that returns the sort key when passed an element.
For example:
$elt->sort_children( sub { $_[0]->att( "nb") + $_[0]->text },
type => 'numeric', order => 'reverse'
);
π field_to_att ($cond, $att)
Turn the text of the first sub-element matched by $cond into the value of attribute $att of the element. If $att is omitted then $cond is used as the name of the attribute, which makes sense only if $cond is a valid element (and attribute) name.
The sub-element is then cut.
π§ att_to_field ($att, $tag)
Take the value of attribute $att and create a sub-element $tag as first child of the element. If $tag is omitted then $att is used as the name of the sub-element.
π₯ get_xpath ($xpath, $optional_offset)
Return a list of elements satisfying the $xpath. $xpath is an XPATH-like expression.
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. (Yep, that note is in the original twice, so here it is twice. π)
π find_nodes
Same as get_xpath.
π findnodes
Same as get_xpath.
π text @optional_options
Return a string consisting of all the PCDATA and CDATA in an element, without any tags. The text is not XML-escaped: base entities such as & and < are not escaped.
The "no_recurse" option will only return the text of the element, not of any included sub-elements (same as text_only).
π¦ text_only
Same as text except that the text returned doesnβt include the text of sub-elements.
πΈ trimmed_text
Same as text except that the text is trimmed: leading and trailing spaces are discarded, consecutive spaces are collapsed.
π set_text ($string)
Set the text for the element: if the element is a PCDATA, just set its text, otherwise cut all the children of the element and create a single PCDATA child for it, which holds the text.
β¨ merge ($elt2)
Move the content of $elt2 within the element.
π«Ά insert ($tag1, [$optional_atts1], $tag2, [$optional_atts2],...)
For each tag in the list inserts an element $tag as the only child of the element. The element gets the optional attributes in $optional_atts<n>. All children of the element are set as children of the new element. The upper level element is returned.
$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>
π wrap_in (@tag)
Wrap elements in @tag as the successive ancestors of the element, returns the new element. $elt->wrap_in( 'td', 'tr', 'table') wraps the element as a single cell in a table for example.
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" });
π
insert_new_elt ($opt_position, $tag, $opt_atts_hashref, @opt_content)
Combines a new and a paste: creates a new element using $tag, $opt_atts_hashref and @opt_content which are arguments similar to those for new, then paste it, using $opt_position or 'first_child', relative to $elt.
Return the newly created element.
π erase
Erase the element: the element is deleted and all of its children are pasted in its place.
π§ set_content ( $optional_atts, @list_of_elt_and_strings) (
$optional_atts, '#EMPTY')
Set the content for the element, from a list of strings and elements. Cuts all the element children, then pastes the list elements as the children. This method will create a PCDATA element for any strings in the list.
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;
π₯ namespace ($optional_prefix)
Return the URI of the namespace that $optional_prefix or the element name belongs to. If the name doesnβt belong to any namespace, undef is returned.
π local_name
Return the local name (without the prefix) for the element.
π ns_prefix
Return the namespace prefix for the element.
π current_ns_prefixes
Return 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, '' appears in the list.
π¦ inherit_att ($att, @optional_tag_list)
Return 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 @optional_tag_list is supplied only those ancestors whose tag is in the list will be checked.
πΈ all_children_are ($optional_condition)
Return 1 if all children of the element pass the $optional_condition, 0 otherwise.
π level ($optional_condition)
Return the depth of the element in the twig (root is 0). If $optional_condition is given then only ancestors that match the condition are counted.
WARNING: in a tree created using thetwig_rootsoption this will not return the level in the document tree, level 0 will be the document root, level 1 will be thetwig_rootselements. During the parsing (in atwig_handler) you can use thedepthmethod on the twig object to get the real parsing depth.
in ($potential_parent)
Returns true if the element is in the $potential_parent (and yes, $potential_parent is an element, bestie, don't try anything else) π
in_context ($cond, $optional_level)
Returns true if the element is included in an element which passes $cond, optionally within $optional_level levels. And the returned value is the including element itself β cute little two-for-one π«Ά
pcdata
Returns the text of a PCDATA element, or undef if the element is not PCDATA, periodt.
pcdata_xml_string
Returns the text of a PCDATA element or undef if the element is not PCDATA. The text is "XML-escaped" β so '&' and '<' get replaced by '&' and '<' β¨
set_pcdata ($text)
Sets the text of a PCDATA element. Ngl this one does not check that the element is actually a PCDATA, so usually you should reach for set_text instead π
append_pcdata ($text)
Adds the text at the end of a PCDATA element, no cap.
is_cdata
Returns 1 if the element is a CDATA element, returns 0 otherwise π«
is_text
Returns 1 if the element is a CDATA or PCDATA element, returns 0 otherwise.
cdata
Returns the text of a CDATA element or undef if the element is not CDATA.
cdata_string
Returns the XML string of a CDATA element, including the opening and closing markers π
set_cdata ($text)
Sets the text of a CDATA element.
append_cdata ($text)
Adds the text at the end of a CDATA element.
remove_cdata
Turns all CDATA sections in the element into regular PCDATA elements. This is so useful when converting XML to HTML, because browsers literally do not support CDATA sections π
extra_data
Returns the extra_data (comments and PI's) attached to an element π
set_extra_data ($extra_data)
Sets the extra_data (comments and PI's) attached to an element.
append_extra_data ($extra_data)
Appends extra_data to the existing extra_data before the element (and if no previous extra_data exists then it is created, slay) β¨
set_asis
Sets a property of the element that causes it to be output without being XML escaped by the print functions: so if it contains a < b it will be output as such and not as a < b. This can be useful to create text elements that will be output as markup π₯
Note that all 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 CDATA element it will also be output asis, without the CDATA markers. Same goes for any CDATA descendant of the element.
set_not_asis
Unsets the "asis" property for the element and its text descendants π
is_asis
Returns the "asis" property status of the element ( 1 or undef ).
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 π (very "am I done yet" energy, honestly).
get_type
Returns the type of the element: "#ELT" for "real" elements, or "#PCDATA", "#CDATA", "#COMMENT", "#ENT", "#PI" π
is_elt
Returns the tag if the element is a "real" element, or 0 if it is PCDATA, CDATA... π
contains_only_text
Returns 1 if the element does not contain any other "real" element.
contains_only ($exp)
Returns the list of children if all children of the element match the expression $exp.
if( $para->contains_only( 'tt')) { ... }
contains_a_single ($exp)
If the element contains a single child that matches the expression $exp, returns that element. Otherwise returns 0 π€·ββοΈ
is_field
Same as contains_only_text.
is_pcdata
Returns 1 if the element is a PCDATA element, returns 0 otherwise.
is_ent
Returns 1 if the element is an entity (an unexpanded entity) element, returns 0 otherwise.
is_empty
Returns 1 if the element is empty, 0 otherwise β
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 up π The only effect of this method is that the output will be <tag att="value"/>.
set_not_empty
Flags the element as not empty. If it is actually empty then the element will be output as <tag att="value"></tag> π¦
is_pi
Returns 1 if the element is a processing instruction ("#PI") element, returns 0 otherwise.
target
Returns the target of a processing instruction.
set_target ($target)
Sets the target of a processing instruction.
data
Returns the data part of a processing instruction.
set_data ($data)
Sets the data of a processing instruction.
set_pi ($target, $data)
Sets the target and the data of a processing instruction β both at once, efficient queen π
pi_string
Returns the string form of a processing instruction: "<?target data?>" β¨
is_comment
Returns 1 if the element is a comment ("#COMMENT") element, returns 0 otherwise.
set_comment ($comment_text)
Sets the text for a comment.
comment
Returns the content of a comment β just the text, not the <!-- and --> π
comment_string
Returns the XML string for a comment: "<!-- comment -->"
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, since 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). Lowkey a trap, bestie π
set_ent ($entity)
Sets an (non-expanded) entity ("#ENT"). $entity) is the entity text ("&ent;") π«Ά
ent
Returns the entity for an entity ("#ENT") element ("&ent;").
ent_name
Returns the entity name for an entity ("#ENT") element ("ent").
ent_string
Returns the entity, either expanded if the expanded version is available, or non-expanded ("&ent;") otherwise β¨
child ($offset, $optional_condition)
Returns the $offset-th child of the element, optionally the $offset-th child that matches $optional_condition. The children are treated as a list, so $elt->child( 0) is the first child, while $elt->child( -1) is the last child π
child_text ($offset, $optional_condition)
Returns the text of a child or undef if the sibling does not exist. Arguments are the same as child.
last_child ($optional_condition)
Returns the last child of the element, or the last child matching $optional_condition (ie the last of the element children matching the condition) π
last_child_text ($optional_condition)
Same as first_child_text but for the last child.
sibling ($offset, $optional_condition)
Returns the next or previous $offset-th sibling of the element, or the $offset-th one matching $optional_condition. If $offset is negative then a previous sibling is returned, if $offset is positive then a next sibling is returned. "$offset=0" returns the element if there is no condition or if the element matches the condition>, "undef" otherwise π«
sibling_text ($offset, $optional_condition)
Returns the text of a sibling or undef if the sibling does not exist. Arguments are the same as sibling.
prev_siblings ($optional_condition)
Returns the list of previous siblings (optionally matching $optional_condition) for the element. The elements are ordered in document order π
next_siblings ($optional_condition)
Returns the list of siblings (optionally matching $optional_condition) following the element. The elements are ordered in document order.
siblings ($optional_condition)
Returns the list of siblings (optionally matching $optional_condition) of the element (excluding the element itself). The elements are ordered in document order β¨
pos ($optional_condition)
Returns the position of the element in the children list. The first child has a position of 1 (as in XPath) πΈ
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.
atts
Returns a hash ref containing the element attributes.
set_atts ({ att1=>$att1_val, att2=> $att2_val... })
Sets the element attributes with the hash ref supplied as the argument. The previous attributes are lost (ie the attributes set by set_atts replace all of the attributes of the element) π
You can also pass a list instead of a hashref: $elt->set_atts( att1 => 'val1',...)
del_atts
Deletes all the element attributes. Gone, bye π
att_nb
Returns the number of attributes for the element π’
has_atts
Returns true if the element has attributes (in fact returns the number of attributes, thus being an alias to att_nb).
has_no_atts
Returns true if the element has no attributes, false (0) otherwise.
att_names
Returns a list of the attribute names for the element π
att_xml_string ($att, $options)
Returns the attribute value, where '&', '<' and quote (" or the value of the quote option at twig creation) are XML-escaped.
The options are passed as a hashref β setting escape_gt to a true value will also escape '>':
$elt( 'myatt', { escape_gt => 1 });
set_id ($id)
Sets the "id" attribute of the element to the value. See elt_id to change the id attribute name π
id
Gets the id attribute value.
del_id ($id)
Deletes the "id" attribute of the element and removes it from the id list for the document β¨
class
Returns the "class" attribute for the element (methods on the "class" attribute are quite convenient when dealing with XHTML, or plain XML that will eventually be displayed using CSS) π
lclass
Same as class, except that this method is an lvalue, so you can do $elt->lclass= "foo" π
set_class ($class)
Sets the "class" attribute for the element to $class.
add_class ($class)
Adds $class to the element "class" attribute: the new class is added only if it is not already present π¦
<pink>remove_class ($class)</pink>
Take $class out of the element's class attribute. Byeee π
heads up bestie: the classes get re-sorted alphabetically after this, so the class attribute string can totally change even if the class was already sitting there.
add_to_class ($class)
Just an alias for add_class. Same energy, different name π«Ά
att_to_class ($att)
Sets the class attribute to whatever value lives in attribute $att.
add_att_to_class ($att)
Takes the value of attribute $att and adds it onto the element's class attribute.
move_att_to_class ($att)
Adds the value of attribute $att to class and deletes $att itself. Moving day πβ¨
tag_to_class
Sets the element's class attribute to its own tag name. Main character move honestly.
add_tag_to_class
Adds the element's tag to its class attribute (doesn't replace what's there).
set_tag_class ($new_tag)
Adds the element's tag to its class attribute, then sets the tag itself to $new_tag.
in_class ($class)
Returns true (1) if the element is in class $class β meaning $class is one of the tokens inside the element's class attribute. Vibe check passed β
tag_to_span
Changes the element's tag to span and sets its class to the old tag.
tag_to_div
Changes the element's tag to div and sets its class to the old tag.
DESTROY
Frees the element from memory. Gone, but not forgotten ππ¦
start_tag
Returns the string for the element's start tag, including the /> at the end of an empty element tag.
end_tag
Returns the string for the element's end tag. For an empty element this returns the empty string ('').
xml_string @optional_options
Equivalent to $elt->sprint( 1) β returns the string for the whole entire element, excluding the element's own tags (but nested element tags are present, no worries).
The "no_recurse" option will only return the text of the element, not of any included sub-elements (same thing as xml_text_only).
inner_xml
Another synonym for xml_string. Same tea, different mug β
outer_xml
Another synonym for sprint.
xml_text
Returns the text of the element, encoded (and run through the current output_filter or output_encoding options), with no tag at all. Just the words π
xml_text_only
Same as xml_text except the text returned doesn't include the text of sub-elements. Strictly the element's own words, no borrowed ones.
set_pretty_print ($style)
Sets the pretty print method. Your options are "none" (the default), "nsgmls", "nice", "indented", "record" and "record_c".
Pretty print styles, bestie, explained:
noneβ the default, no\nused at all. Zero drama, zero newlines.nsgmlsβ nsgmls style, with\nadded inside tags.niceβ adds\nwherever possible (NOT SAFE, can lead to invalid XML π).indentedβ same as"nice"plus it indents elements (NOT SAFE, can lead to invalid XML).recordβ table-oriented pretty print, one field per line.record_cβ table-oriented pretty print, more compact than"record", one record per line.
for real though,"nice"and"indented"can produce invalid XML. Consider yourself warned π«Ά
set_empty_tag_style ($style)
Sets the method used to output empty tags. Pick from "normal" (the default), "html", and "expand".
"normal" outputs an empty tag "<tag/>", "html" adds a space "<tag />" for elements that can be empty in XHTML, and "expand" outputs "<tag></tag>". Choose your fighter β¨
set_remove_cdata ($flag)
Sets (or unsets) the flag that forces the twig to output CDATA sections as regular (escaped) PCDATA.
set_indent ($string)
Sets the indentation for the indented pretty print style (default is 2 spaces). Yes you can make it 4. Or a tab. Or chaos π
set_quote ($quote)
Sets the quotes used for attributes. Can be "double" (default) or "single".
cmp ($elt)
Compares the order of the 2 elements in a twig. $a is the <A>..</A> element, $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
before ($elt)
Returns 1 if $elt starts before the element, 0 otherwise. If the 2 elements aren't in the same twig, you get undef.
if( $a->cmp( $b) == -1) { return 1; } else { return 0; }
after ($elt)
Returns 1 if $elt starts after the element, 0 otherwise. If the 2 elements aren't in the same twig, you get undef.
if( $a->cmp( $b) == -1) { return 1; } else { return 0; }
other comparison methods
ltlegtge
path
Returns the element context in a form similar to XPath's short form: "/root/tag1/../tag". Lowkey iconic navigation π§
xpath
Returns a unique XPath expression you can use to find that element all over again. It looks like /doc/sect[3]/title β unique elements don't get an index, the others do.
flush
Flushes the twig up to the current element (strictly equivalent to $elt->root->flush).
private methods
Low-level methods on the twig:
set_parent ($parent)set_first_child ($first_child)set_last_child ($last_child)set_prev_sibling ($prev_sibling)set_next_sibling ($next_sibling)set_twig_currentdel_twig_currenttwig_currentcontains_text
Those methods should not be used β unless of course you find some creative and interesting, not to mention useful, ways to do it πβ¨
π cond
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:
#ELTβ return a "real" element (not a PCDATA, CDATA, comment or pi element).#TEXTβ return a PCDATA or CDATA element.- regular expression β return an element whose tag matches the regexp. The regexp has to be created with
qr//(hence this is available only on perl 5.005 and above). - code reference β applies the code, passing the current element as argument. If the code returns true then the element is returned; if it returns false then the code is applied to the next candidate.
π¦ XML::Twig::XPath
XML::Twig implements a subset of XPath through the get_xpath method.
If you want the whole XPath power, bestie, then 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. No install, no slay π
See XML::XPath for more information.
The methods you can use are:
findnodes ($path)
Return a list of nodes found by $path.
findnodes_as_string ($path)
Return the nodes found, reproduced as XML. The result is not guaranteed to be valid XML though. π
findvalue ($path)
Return the concatenation of the text content of the result nodes.
In order for XML::XPath to be used as the XPath engine, the following methods are included in XML::Twig:
in XML::Twig:
getRootNodegetParentNodegetChildNodes
in XML::Twig::Elt:
string_valuetoStringgetNamegetRootNodegetNextSiblinggetPreviousSiblingisElementNodeisTextNodeisPIisPINodeisProcessingInstructionNodeisCommentisCommentNodegetTargetgetChildNodesgetElementById
πΈ XML::Twig::XPath::Elt
The methods you can use are the same as on XML::Twig::XPath elements:
findnodes ($path)β return a list of nodes found by$path.findnodes_as_string ($path)β return the nodes found, reproduced as XML. The result is not guaranteed to be valid XML though.findvalue ($path)β return the concatenation of the text content of the result nodes.
π XML::Twig::Entity_list
newβ create an entity list.add ($ent)β add an entity to an entity list.add_new_ent ($name, $val, $sysid, $pubid, $ndata, $param)β create a new entity and add it to the entity list.delete ($ent or $tag)β delete an entity (defined by its name or by the Entity object) from the list.print ($optional_filehandle)β print the entity list.listβ return the list as an array.
π XML::Twig::Entity
new ($name, $val, $sysid, $pubid, $ndata, $param)β same arguments as the Entity handler forXML::Parser.print ($optional_filehandle)β print an entity declaration.nameβ return the name of the entity.valβ return the value of the entity.sysidβ return the system id for the entity (for NDATA entities).pubidβ return the public id for the entity (for NDATA entities).ndataβ return true if the entity is an NDATA entity.paramβ return true if the entity is a parameter entity.textβ return the entity declaration text.
π XML::Twig::Notation_list
newβ create a notation list.add ($notation)β add a notation to a notation list.add_new_notation ($name, $base, $sysid, $pubid)β create a new notation and add it to the notation list.delete ($notation or $tag)β delete a notation (defined by its name or by the Notation object) from the list.sprintβ return the notation list as a string.print ($optional_filehandle)β print the notation list.listβ return the list as an array.
π XML::Twig::Notation
new ($name, $base, $sysid, $pubid)β same arguments as the Notation handler forXML::Parser.print ($optional_filehandle)β print a notation declaration.nameβ return the name of the notation.baseβ return the base to be used for resolving a relative URI.sysidβ return the system id for the notation.pubidβ return the public id for the notation.textβ return the notation declaration text.
β¨ EXAMPLES β¨
More examples (and a whole complete tutorial) live on the XML::Twig Page <http://www.xmltwig.org/xmltwig/> π«Ά
Wanna figure out what flush actually does? Run 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";
πΈ NOTES πΈ
okay bestie, this is the notes zone β the βread this before you text me asking why something is weirdβ part. π
π§ Subclassing XML::Twig
Useful methods:
π elt_class
If you're subclassing XML::Twig, you'll probs also need to subclass XML::Twig::Elt. Use the elt_class option when you create the XML::Twig object so elements get created in a different class (which should be a subclass of XML::Twig::Elt). β¨
π add_options
If you inherit the XML::Twig new method but want to add more options to it, use this method so XML::Twig doesn't warn about those extra options. π«Ά
π DTD Handling
There are 3 possibilities here. They are:
πΌ No DTD
No doctype, no DTD information, no entity information β the world is simple... π¦
πΌ Internal DTD
The XML document includes an internal DTD, and maybe entity declarations.
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 get flushed (or printed) either as is (if they have not been modified) or as reconstructed (poorly β comments are lost, order is not kept; due to its 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).
πΌ External DTD
The XML document includes a reference to an external DTD, and maybe entity declarations.
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 flushed (or printed) 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. π
π¦ Flush
Remember that element handlers are called when the element is CLOSED, so with nested elements the inner handlers get called first. That makes numbering nested sections (or clauses, or divs) trickier than it seems, because the titles in the inner sections are handled before the outer sections. π
π BUGS π
π©Ή segfault during parsing
This happens when parsing huge documents, or lots of small ones, with a version of Perl before 5.16.
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).
NOT RECOMMENDED: another 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.
π©Ή entity handling
Due to XML::Parser behaviour, non-base entities in attribute values disappear if they are not declared in the document: att="val&ent;" will be turned into att => val, unless you use the keep_encoding argument to XML::Twig->new. π
π©Ή DTD handling
The DTD handling methods are quite bugged. No one uses them and it seems very difficult to get them to work in all cases, including with several slightly incompatible versions of XML::Parser and of libexpat.
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. π
π©Ή memory leak
If you use a REALLY old Perl (5.005!) and a lot of twigs, you might find that you leak quite a lot of memory (about 2Ks per twig). You can use the dispose method to free that memory after you are done.
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. π§
π©Ή ID list
The ID list is NOT updated when elements are cut or deleted. Periodt. π
π©Ή change_gi
This method will not function properly if you do:
$twig->change_gi( $old1, $new);
$twig->change_gi( $old2, $new);
$twig->change_gi( $new, $even_newer);
π©Ή sanity check on XML::Parser method calls
XML::Twig should really prevent calls to some XML::Parser methods, especially the setHandlers method.
π©Ή pretty printing
Pretty printing (at least using the "indented" style) is hard to get right! Only elements that belong to the document will be properly indented. Printing elements that do not belong to the twig makes it impossible for XML::Twig to figure out their depth, and thus their indentation level.
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. π
π Globals π
These are the things that can mess up calling code, especially if threaded. They might also cause problems under mod_perl.
β Exported constants
Whether you want them or not you get them! These are subroutines to use as constants when creating or testing elements:
PCDATA return '#PCDATA'
CDATA return '#CDATA'
PI return '#PI', I had the choice between PROC and PI :--(
β Module scoped values: constants
These should cause no trouble:
%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);
β Module scoped values: might be changed
Most of these deal with pretty printing, so the worst that can happen is probably that XML output does not look right, but is still valid and processed identically by XML processors.
$empty_tag_style can mess up HTML browsers 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)
β Module scoped values: definitely changed
These 2 variables are used to replace tags by an index, thus saving some space when creating a twig. If they really cause you too much trouble, let me know, it is probably possible to create either a switch or at least a version of XML::Twig that does not perform this optimization.
%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:
π«Ά global_state
Return a hashref with all the global variables used by XML::Twig.
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.
π«Ά set_global_state ($state)
Set the global state, $state is a hashref.
π«Ά save_global_state
Save the current global state.
π«Ά restore_global_state
Restore the previously saved state (using Lsave_global_state> state).
β TODO β
π± SAX handlers
Allowing XML::Twig to work on top of any SAX parser.
π± multiple twigs are not well supported
A number of twig features are just global at the moment. These include the ID list and the "tag pool" (if you use change_gi then you change the tag for ALL twigs).
A future version will try to support this while trying not to be too hard on performance (at least when a single twig is used!). π₯
π AUTHOR π
Michel Rodriguez <mirod@cpan.org>
π LICENSE π
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>
β¨ SEE ALSO β¨
okay so if you want the full lore, bestie: the complete docs β including a tutorial, examples, an easier-to-use HTML version of the docs, a quick reference card, and a FAQ β are all available at http://www.xmltwig.org/xmltwig/ π¦
Thereβs also a git repository at http://github.com/mirod/xmltwig π
And go peep these related modules too: XML::Parser, XML::Parser::Expat, XML::XPath, Encode, Text::Iconv, and Scalar::Utils β¨
π¦ Alternative Modules π¦
okay so first thing: XML::Twig is not the only XML::Processing module available on CPAN β far from it, bestie! π
The main alternative I would recommend is XML::LibXML π
Quick comparison of the 2 modules, letβs go:
XML::LibXML β actually libxml2, which itβs based on β sticks to the standards and implements a good number of them in a rather strict way: XML, XPath, DOM, RelaxNG, and 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 lets 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, it 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/) β
π And thatβs the whole manual, bestie! Source/version check: perl v5.42.0, dated 2025-01-16, and this iconic manual is Twig(3). Go be the main character of your XML processing era πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-XML-Twig 3.530.0-160000.2.2 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms