- NAME
- SYNOPSIS
- DESCRIPTION
- XML::Twig 101
- Simplifying XML processing
- CLASSES
- METHODS
- XML::Twig
- Methods inherited from XML::Parser::Expat
- add_stylesheet
- change_gi
- create_accessors
- dispose
- doctype
- dtd
- dtd_print
- dtd_text
- elt_id
- encoding
- entity
- entity_list
- entity_names
- find_nodes
- findnodes
- findvalue
- finish
- finish_print
- first_elt
- flush
- flush_toSAX1
- flush_toSAX2
- flush_up_to
- getEltById
- get_xpath
- ignore
- index
- last_elt
- model
- new
- DTD_handler
- char_handler
- comments
- discard_spaces
- discard_spaces_in
- do_not_chain_handlers
- elt_class
- empty_tags
- end_tag_handlers
- expand_external_ents
- id
- ignore_elts
- index
- input_filter
- keep_atts_order
- keep_encoding
- keep_original_prefix
- keep_spaces
- keep_spaces_in
- load_DTD
- map_xmlns
- no_prolog
- output_encoding
- output_filter
- output_text_filter
- parse_start_tag
- pi
- pretty_print
- quote
- remove_cdata
- start_tag_handlers
- twig_handlers
- twig_print_outside_roots
- twig_roots
- nparse
- nparse_e
- nparse_pp
- nparse_ppe
- parse
- parse_html
- parsefile
- parsefile_html
- parsefile_html_inplace
- parsefile_inplace
- parser
- parsestring
- parseurl
- path
- print_prolog
- print_to_file
- prolog
- purge
- purge_up_to
- root
- safe_parse
- safe_parsefile
- safe_parseurl
- setCharHandler
- setEndTagHandler
- setEndTagHandlers
- setIgnoreEltsHandler
- setIgnoreEltsHandlers
- setStartTagHandler
- setStartTagHandlers
- setTwigHandler
- setTwigHandlers
- setTwigRoots
- set_do_not_escape_amp_in_atts
- set_doctype
- set_empty_tag_style
- set_encoding
- set_expand_external_entities
- set_input_filter
- set_keep_atts_order
- set_keep_encoding
- set_output_encoding
- set_output_filter
- set_output_text_filter
- set_pretty_print
- set_remove_cdata
- set_root
- set_standalone
- set_xml_version
- sprint
- standalone
- subs_text
- toSAX1
- toSAX2
- trim
- xml_version
- xmldecl
- xparse
- XML::Twig::Elt
- DESTROY
- add_att_to_class
- add_id
- add_tag_to_class
- add_to_class
- after
- all_children_are
- ancestors
- ancestors_or_self
- append_cdata
- append_extra_data
- append_pcdata
- att
- att_names
- att_nb
- att_to_class
- att_to_field
- att_xml_string
- atts
- before
- cdata
- cdata_string
- change_att_name
- child
- child_text
- children
- children_copy
- children_count
- children_text
- children_trimmed_text
- class
- closed
- cmp
- comment
- comment_string
- contains_a_single
- contains_only
- contains_only_text
- copy
- current_ns_prefixes
- cut
- cut_children
- data
- del_att
- del_atts
- del_id
- delete
- descendants
- descendants_or_self
- end_tag
- ent
- ent_name
- ent_string
- erase
- extra_data
- field
- field_to_att
- find_by_tag_name
- find_nodes
- findnodes
- first_child
- first_child_matches
- first_child_text
- first_descendant
- following_elt
- following_elts
- former_next_sibling
- former_parent
- former_prev_sibling
- getElementsByTagName
- get_type
- get_xpath
- gi
- has_atts
- has_child
- has_children
- has_no_atts
- id
- in
- in_class
- in_context
- inherit_att
- inner_xml
- insert
- insert_new_elt
- is_asis
- is_cdata
- is_comment
- is_elt
- is_empty
- is_ent
- is_field
- is_first_child
- is_last_child
- is_pcdata
- is_pi
- is_text
- last_child
- last_child_text
- last_descendant
- level
- local_name
- mark
- merge
- move
- move_att_to_class
- name
- namespace
- new
- next_elt
- next_n_elt
- next_sibling
- next_siblings
- ns_prefix
- other comparison methods
- outer_xml
- parent
- parse
- passes
- paste
- path
- pcdata
- pcdata_xml_string
- pi_string
- pos
- preceding_elt
- preceding_elts
- prefix
- prev_elt
- prev_sibling
- prev_siblings
- private methods
- remove_cdata
- replace
- replace_with
- root
- set_asis
- set_att
- set_atts
- set_cdata
- set_class
- set_comment
- set_content
- set_data
- set_empty
- set_empty_tag_style
- set_ent
- set_extra_data
- set_field
- set_gi
- set_id
- set_id_seed
- set_indent
- set_inner_html
- set_inner_xml
- set_name
- set_not_asis
- set_not_empty
- set_pcdata
- set_pi
- set_pretty_print
- set_quote
- set_remove_cdata
- set_tag
- set_tag_class
- set_target
- set_text
- sibling
- sibling_text
- simplify
- sort_children
- sort_children_on_att
- sort_children_on_field
- sort_children_on_value
- split
- split_at
- sprint
- start_tag
- strip_att
- subs_text
- suffix
- tag
- tag_to_class
- tag_to_div
- tag_to_span
- target
- text @optional_options
- text_only
- trim
- trimmed_field
- trimmed_text
- twig
- wrap_children
- wrap_in
- xml_string @optional_options
- xml_text
- xml_text_only
- xpath
- cond
- XML::Twig::XPath
- XML::Twig::XPath::Elt
- XML::Twig::Entity_list
- XML::Twig::Entity
- XML::Twig
- EXAMPLES
- NOTES
- BUGS
- Globals
- TODO
- AUTHOR
- LICENSE
- SEE ALSO
NAME
XML::Twig - A perl module for processing huge XML documents in tree mode.
SYNOPSIS
Note that this documentation is intended as a reference to the module.
Complete docs, including a tutorial, examples, an easier to use HTML version, a quick reference card and a FAQ are available at http://www.xmltwig.com/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
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->flush; # flush the end of the documentSee 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 build on top of XML::Parser.
The module offers a tree interface to the document, while allowing you to output the parts of it that have been completely processed.
It allows minimal resource (CPU and memory) usage by building the tree only for the parts of the documents that need actual processing, through the use of the twig_roots and twig_print_outside_roots options. The finish and finish_print methods also help to increase performances.
XML::Twig tries to make simple things easy so it tries its best to takes care of a lot of the (usually) annoying (but sometimes necessary) features that come with XML and XML::Parser.
XML::Twig 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 documentOther useful methods include:
att: $elt->{'att'}->{'foo'} return the foo attribute for an element,
set_att : $elt->set_att( foo => "bar") sets the foo attribute to the bar value,
next_sibling: $elt->{next_sibling} return the next sibling in the document (in the example $title->{next_sibling} is the first para, you can also (and actually should) use $elt->next_sibling( 'para') to get it
The document can also be transformed through the use of the cut, copy, paste and move methods: $title->cut; $title->paste( after => $p); for example
And much, much more, see Elt.
Processing an XML document chunk by chunk
One of the strengths of XML::Twig is that it let you work with files that do not fit in memory (BTW storing an XML document in memory as a tree is quite memory-expensive, the expansion factor being often around 10).
To do this you can define handlers, that will be called once a specific element has been completely parsed. In these handlers you can access the element and process it as you see fit, using the navigation and the cut-n-paste methods, plus lots of convenient ones like prefix . Once the element is completely processed you can then flush it, which will output it and free the memory. You can also purge it if you don't need to output it (if you are just extracting some data from the document for example). The handler will be called again once the next relevant element has been parsed.
my $t= XML::Twig->new( twig_handlers =>
{ section => \§ion,
para => sub { $_->set_tag( 'p');
},
);
$t->parsefile( 'doc.xml');
$t->flush; # don't forget to flush one last time in the end or anything
# after the last </section> tag will not be output
# 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.4, my favourite method...
# 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 documents but are not interested in the rest and you don't want to pay the price, either in time or memory, to build the tree for the it.
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:
Before being uploaded to CPAN, XML::Twig 3.22 has been tested under the following environments:
linux-x86
perl 5.6.2, expat 1.95.8, XML::Parser 2.34 perl 5.8.0, expat 1.95.8, XML::Parser 2.34 perl 5.8.7, expat 1.95.8, XML::Parser2.34
Solaris
perl 5.6.1, expat 1.95.2, XML::Parser 2.31
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.com/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 garantee 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
Whitespaces that look non-significant are discarded, this behaviour can be controlled using the keep_spaces , keep_spaces_in and discard_spaces_in options.
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
You can also use output_encoding to convert the internal UTF-8 format to the required encoding.
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)
Pretty Printing
XML::Twig can output the document pretty printed so it is easier to read for us humans.
Surviving an untimely death
XML parsers are supposed to react violently when fed improper XML. XML::Parser just dies.
XML::Twig provides the safe_parse and the safe_parsefile methods which wrap the parse in an eval and return either the parsed twig or 0 in case of failure.
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.
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.
You might want to look the elt_class option if you want to subclass XML::Twig::Elt.
Attributes are just attached to their parent element, they are not objects per se. (Please use the provided methods att and set_att to access them, if you access them as a hash, then your code becomes implementaion deppndant and might break in the future).
Other classes that are seldom used are XML::Twig::Entity_list and XML::Twig::Entity.
If you use XML::Twig::XPath instead of XML::Twig, elements are then created as XML::Twig::XPath::Elt
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
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 XML::Twig specifics.
New Options:
twig_handlers
This argument consists of a hash { expression = \&handler}> where expression is a 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, or string(<tag>) function (except in twig_roots triggers).
Additionally you can use regexps (/ delimited) to match attribute and string values.
Examples:
foo foo/bar foo//bar /foo/bar /foo//bar /foo/bar[@att1 = "val1" and @att2 = "val2"]/baz[@a >= 1] foo[string()=~ /^duh!+/] /foo[string(bar)=~ /\d+/]/baz[@att != 3]
#CDATA can be used to call a handler for a CDATA. #COMMENT can be used to call a handler for comments
Some additional (non-XPath) expressions are also provided for convenience:
'?' 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').
Triggers the handler for all elements in the tree
Triggers the handler for each element that does NOT have any other handler.
Triggers the handler on any element at that level in the tree (root is level 1)
_all_
_default_
level(<level>)
processing instructions
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 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, exept 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, rince, 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 explicitely return a short true value (like 1) from handlers: this ensures that other applicable handlers are called even if the last statement for the handler happens to evaluate to false. This might also speedup the code by avoiding the result of the last statement of the code to be copied and passed to the code managing handlers. It can really pay to have 1 instead of a long string returned.
When an element is CLOSED 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. This 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 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).
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.
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.
If the value is a reference to a file handle then the document outside the twig_roots elements will be output to this file handle:
open( OUT, ">out_file") or die "cannot open out file 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}>. Sets element handlers that are called when the element is open (at the end of the XML::Parser Start handler). The handlers are called with 2 params: the twig and the element. The element is empty at that point, its attributes are created though.
You can use generic_attribute_condition, attribute_condition, full_path, partial_path, tag, tag_regexp, _default_ and _all_ to trigger the handler.
string_condition and regexp_condition cannot be used as the content of the element, and the string, have not yet been parsed when the condition is checked.
The main uses for those handlers are to change the tag name (you might have to do it as soon as you find the open tag if you plan to flush the twig at some point in the element, and to create temporary attributes that will be used when processing sub-element with twig_hanlders.
You should also use it to change tags if you use flush. If you change the tag in a regular twig_handler then the start tag might already have been flushed.
Note: start_tag handlers can be called outside of twig_roots if this argument is used, in this case handlers are called with the following arguments: $t (the twig), $tag (the tag of the element) and %att (a hash of the attributes of the element).
If the twig_print_outside_roots argument is also used, if the last handler called returns a true value, then the the start tag will be output as it appeared in the original document, if the handler returns a a false value then the start tag will not be printed (so you can print a modified string yourself for example).
Note that you can use the ignore method in start_tag_handlers (and only there).
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). The handlers are called with 2 params: the twig and the tag of the element.
twig_handlers are called when an element is completely parsed, so why have this redundant option? There is only one use for end_tag_handlers: when using the twig_roots option, to trigger a handler for an element outside the roots. It is for example very useful to number titles in a document using nested sections:
my @no= (0);
my $no;
my $t= XML::Twig->new(
start_tag_handlers =>
{ section => sub { $no[$#no]++; $no= join '.', @no; push @no, 0; } },
twig_roots =>
{ title => sub { $_[1]->prefix( $no); $_[1]->print; } },
end_tag_handlers => { section => sub { pop @no; } },
twig_print_outside_roots => 1
);
$t->parsefile( $file);Using the end_tag_handlers argument without twig_roots will result in an error.
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 regardeless
ignore_elts
This option lets you ignore elements when building the twig. This is 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.
Example:
my $twig= XML::Twig->new( ignore_elts => { elt => 1 });
$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.
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;
}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.
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 outputing the attributes in the same order as they were in the original document.
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 theExpat 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)
WARNING: this option is NOT used when parsing with the non-blocking parser (parse_start, parse_more, parse_done methods) which you probably should not use with XML::Twig anyway as they are totally untested!
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
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:
my $conv = XML::Twig::encode_convert( 'latin1'); my $t = XML::Twig->new(output_filter => $conv);
my $conv = XML::Twig::iconv_convert( 'latin1'); my $t = XML::Twig->new(output_filter => $conv);
my $conv = XML::Twig::unicode_convert( 'latin1'); my $t = XML::Twig->new(output_filter => $conv);
Return a subref that can be used to convert utf8 strings to $encoding). Uses Encode.
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
does the same conversion as latin1, plus encodes entities using HTML::Entities (oddly enough you will need to have HTML::Entities intalled 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
encode_convert ($encoding)
html
iconv_convert ($encoding)
latin1
safe
safe_hex
same as safe except that the character entities are in hexa (&#xnnn;)
this function is used to create a filter subroutine that will be used to convert the characters to the target encoding using Text::Iconv (which needs to be installed, look at the documentation for the module and for the iconv library to find out which encodings are available on your system)
this function is used to create a filter subroutine that will be used to convert the characters to the target encoding using Unicode::Strings and Unicode::Map8 (which need to be installed, look at the documentation for the modules to find out which encodings are available on your system)
unicode_convert ($encoding)
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-1 (aka latin1)
The text and att methods do not use the filter, so their result are always in unicode.
Those predeclared filters are based on subroutines that can be used by themselves (as XML::Twig::foo).
Use HTML::Entities to encode a utf8 string
Use a regexp to encode a utf8 string into latin 1 (ISO-8859-1). Does not work with Perl 5.8.0!
Use either a regexp (perl < 5.8) or Encode to encode non-ascii characters in the string in &#<nnnn>; format
Use either a regexp (perl < 5.8) or Encode to encode non-ascii characters in the string in &#x<nnnn>; format
html_encode ($string)
regexp2latin1 ($string)
safe_encode ($string)
safe_encode_hex ($string)
output_text_filter
same as output_filter, except it doesn't apply to the brackets and quotes around attribute values. This is useful for all filters that could change the tagging, basically anything that does not just change the encoding of the output. html, safe and safe_hex are better used with this option.
input_filter
This option is similar to output_filter except the filter is applied to the characters before they are stored in the twig, at parsing time.
remove_cdata
Setting this option to a true value will force the twig to output CDATA sections as regular (escaped) PCDATA
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).
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 whith a tag '#ENT', the entity will not be expanded there, so you might want to process the entities before outputting it.
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_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)
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 are discarded. This argument is set to true by default.
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.
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.
pretty_print
Set the pretty print method, amongst 'none' (default), 'nsgmls', 'nice', 'indented', 'indented_c', wrapped, 'record' and 'record_c'
pretty_print formats:
<!ELEMENT foo (#PCDATA|bar)>
<foo> <bar>bar is just pcdata</bar> </foo>
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.
Same as indented but a little more compact: the closing tags are on the same line as the preceeding text
Same as indented_c but lines are wrapped using Text::Wrap::wrap. The default length for lines is the default for $Text::Wrap::columns, and can be changed by changing that variable.
Same as nice (and with the same warning) but indents elements according to their level
Stands for record compact, one record per line
The document is output as one ling string, with no line breaks except those found within text elements
This is a record-oriented pretty print, that display data in records, one field per line (which looks a LOT like indented)
This is how the SGML parser sgmls splits documents, hence the name.
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!
This is quite ugly but better than none, and it is very safe, the document will still be valid (conforming to its DTD).
This option inserts line breaks before any tag that does not contain text (so element with textual content are not broken as the \n is the significant).
WARNING: this option leaves the document well-formed but might make it invalid (not conformant to its DTD). If you have elements declared as
indented
indented_c
nice
none
nsgmls
record
record_c
then a foo element including a bar one will be printed as
wrapped
empty_tags
Set the empty tag display style ('normal', 'html' or '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>'
quote
Set the quote character for attributes ('single' or 'double').
comments
Set the way comments are processed: 'drop' (default), 'keep' or 'process'
Comments processing options:
<p>text <!-- comment --> more text --></p>
Any use of set_pcdata on the #PCDATA element (directly or through other methods like set_content) will delete the comment(s).
Consider using process if you are outputing SAX events from XML::Twig.
Note: comments in the middle of a text element such as
are kept at their original position in the text. Using ˝"print" methods like print or sprint will return the comments in the text. Using text or field on the other hand will not.
comments are loaded and will appear on the output, they are not accessible within the twig and will not interfere with processing though
comments are loaded in the twig and will be treated as regular elements (their tag is #COMMENT) this can interfere with processing if you expect $elt->{first_child} to be an element but find a comment there. Validation will not protect you from this as comments can happen anywhere. You can use $elt->first_child( 'tag') (which is a good habit anyway) to get where you want.
drop
drops the comments, they are not read, nor printed to the output
keep
process
pi
Set the way processing instructions are processed: 'drop', 'keep' (default) or 'process'
Note that you can also set PI handlers in the twig_handlers option:
'?' => \&handler '?target' => \&handler 2
The handlers will be called with 2 parameters, the twig and the PI element if pi is set to process, and with 3, the twig, the target and the data if pi is set to keep. Of course they will not be called if pi is set to drop.
If pi is set to keep the handler should return a string that will be used as-is as the PI text (it should look like " <?target data? >" or '' if you want to remove the PI),
Only one handler will be called, ?target or ? if no specific handler for that target is available.
map_xmlns
This option is passed a hashref that maps uri's to prefixes. The prefixes in the document will be replaced by the ones in the map. The mapped prefixes can (actually have to) be used to trigger handlers, navigate or query the document.
Here is an example:
my $t= XML::Twig->new( map_xmlns => {'http://www.w3.org/2000/svg' => "svg"},
twig_handlers =>
{ 'svg:circle' => sub { $_->set_att( r => 20) } },
pretty_print => 'indented',
)
->parse( '<doc xmlns:gr="http://www.w3.org/2000/svg">
<gr:circle cx="10" cy="90" r="10"/>
</doc>'
)
->print;This will output:
<doc xmlns:svg="http://www.w3.org/2000/svg">
<svg:circle cx="10" cy="90" r="20"/>
</doc>keep_original_prefix
When used with map_xmlns this option will make XML::Twig use the original namespace prefixes when outputing a document. The mapped prefix will still be used for triggering handlers and in navigation and query methods.
my $t= XML::Twig->new( map_xmlns => {'http://www.w3.org/2000/svg' => "svg"},
twig_handlers =>
{ 'svg:circle' => sub { $_->set_att( r => 20) } },
keep_original_prefix => 1,
pretty_print => 'indented',
)
->parse( '<doc xmlns:gr="http://www.w3.org/2000/svg">
<gr:circle cx="10" cy="90" r="10"/>
</doc>'
)
->print;This will output:
<doc xmlns:gr="http://www.w3.org/2000/svg">
<gr:circle cx="10" cy="90" r="20"/>
</doc>index ($arrayref or $hashref)
This option creates lists of specific elements during the parsing of the XML. It takes a reference to either a list of triggering expressions or to a hash name => expression, and for each one generates the list of elements that match the expression. The list can be accessed 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);Note that the index is not maintained after the parsing. If elements are deleted, renamed or otherwise hurt during processing, the index is NOT updated.
Note: I _HATE_ the Java-like name of arguments used by most XML modules. So in pure TIMTOWTDI fashion all arguments can be written either as UglyJavaLikeName or as readable_perl_name: twig_print_outside_roots or TwigPrintOutsideRoots (or even twigPrintOutsideRoots {shudder}). XML::Twig normalizes them before processing them.
parse ( $source)
The $source parameter should either be a string containing the whole XML document, or it should be an open IO::Handle. Constructor options to XML::Parser::Expat given as keyword-value pairs may follow the$source parameter. These override, for this call, any options or attributes passed through from the XML::Parser instance.
A die call is thrown if a parse error occurs. Otherwise it will return the twig built by the parse. Use safe_parse if you want the parsing to return even when an error occurs.
parsestring
This is just an alias for parse for backwards compatibility.
parsefile (FILE [, OPT => OPT_VALUE [...]])
Open FILE for reading, then call parse with the open handle. The file is closed no matter how parse returns.
A die call is thrown if a parse error occurs. Otherwise it will return the twig built by the parse. Use safe_parsefile if you want the parsing to return even when an error occurs.
parsefile_inplace ( $file, $optional_extension)
Parse and update a file "in place". It does this by creating a temp file, selecting it as the default for print() statements (and methods), then parsing the input file. If the parsing is successful, then the temp file is moved to replace the input file.
If an extension is given then the original file is backed-up (the rules for the extension are the same as the rule for the -i option in perl).
parsefile_html_inplace ( $file, $optional_extension)
Same as parsefile_inplace, except that it parses HTML instead of XML
parseurl ($url $optional_user_agent)
Gets the data from $url and parse 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.
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.
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
parse 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 get an extra CDATA section inside ( <!-- foo --> becomes <!-- <![CDATA[ foo ]]> -->
parsefile_html
parse an HTML file (by converting it to XML using HTML::TreeBuilder, which needs to be available). The file is loaded completely in memory and converted to XML before being parsed.
Alpha: implementation, and thus generated XML could change.
xparse ($thing_to_parse)
parse 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.
nparse ($optional_twig_options, $thing_to_parse)
create a twig with the $optional_options, and parse 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)
Set 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)
Set 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)
Set 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)
Set 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)
Set 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)
Set 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)
Set a char_handler
setIgnoreEltsHandler ($exp)
Set a ignore_elt handler (elements that match $exp will be ignored
setIgnoreEltsHandlers ($exp)
Set all ignore_elt handlers (previous handlers are replaced)
dtd
Return the dtd (an XML::Twig::DTD object) of a twig
xmldecl
Return the XML declaration for the document, or a default one if it doesn't have one
doctype
Return the doctype for the document
dtd_text
Return the DTD text
dtd_print
Print the DTD
model ($tag)
Return the model (in the DTD) for the element $tag
root
Return the root element of a twig
set_root ($elt)
Set the root of a twig
first_elt ($optional_condition)
Return the first element matching $optional_condition of a twig, if no condition is given then the root is returned
last_elt ($optional_condition)
Return 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)
Return the element whose id attribute is $id
getEltById
Same as elt_id
index ($index_name, $optional_index)
If the $optional_index argument is present, return the corresponding element in the index (created using the index option for XML::Twig-new>)
If the argument is not present, return an arrayref to the index
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
This method returns the XML version, as defined by the version attribute in the XML declaration (ie it is undef if the attribute is not defined)
set_xml_version
This method sets the value of the version attribute in the XML declaration. If the declaration did not exist it is created.
standalone
This method returns the value of the standalone declaration for the document
set_standalone
This method sets the value of the standalone 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)
set_output_encoding
Set the encoding "attribute" in the XML declaration
set_doctype ($name, $system, $public, $internal)
Set the doctype of the element. If an argument is undef (or not present) then its former value is retained, if a false ('' or 0) value is passed then the former value is deleted;
entity_list
Return the entity list of a twig
entity_names
Return the list of all defined entities
entity ($entity_name)
Return the entity
change_gi ($old_gi, $new_gi)
Performs a (very fast) global change. All elements $old_gi are now $new_gi. This is a bit dangerous though and should be avoided if < possible, as the new tag might be ignored in subsequent processing.
See BUGS
flush ($optional_filehandle, %options)
Flushes a twig up to (and including) the current element, then deletes all unnecessary elements from the tree that's kept in memory. flush keeps track of which elements need to be open/closed, so if you flush from handlers you don't have to worry about anything. Just keep flushing the twig every time you're done with a sub-tree and it will come out well-formed. After the whole parsing don't forget toflush one more time to print the end of the document. The doctype and entity declarations are also printed.
flush take an optional filehandle as an argument.
options: use the update_DTD option if you have updated the (internal) DTD and/or the entity list and you want the updated DTD to be output
The pretty_print option sets the pretty printing of the document.
Example: $t->flush( Update_DTD => 1);
$t->flush( $filehandle, pretty_print => 'indented');
$t->flush( \*FILE);flush_up_to ($elt, $optional_filehandle, %options)
Flushes up to the $elt element. This allows you to keep part of the tree in memory when you flush.
options: see flush.
purge
Does the same as a flush except 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 $elt element. This allows you to keep part of the tree in memory when you purge.
print ($optional_filehandle, %options)
Prints the whole document associated with the twig. To be used only AFTER the parse.
options: see flush.
print_to_file ($filename, %options)
Prints the whole document associated with the twig to file $filename. To be used only AFTER the parse.
options: see flush.
sprint
Return the text of the whole document associated with the twig. To be used only AFTER the parse.
options: see flush.
trim
Trim the document: gets rid of initial and trailing spaces, and relace multiple spaces by a single one.
toSAX1 ($handler)
Send SAX events for the twig to the SAX1 handler $handler
toSAX2 ($handler)
Send SAX events for the twig to the SAX2 handler $handler
flush_toSAX1 ($handler)
Same as flush, except that SAX events are sent to the SAX1 handler $handler instead of the twig being printed
flush_toSAX2 ($handler)
Same as flush, except that SAX events are sent to the SAX2 handler $handler instead of the twig being printed
ignore
This method hould be called during parsing, usually in start_tag_handlers. It causes the element to be skipped during the parsing: the twig is not built for this element, it will not be accessible during parsing or after it. The element will not take up any memory and parsing will be faster.
Note that this method can also be called on an element. If the element is a parent of the current element then this element will be ignored (the twig will not be built any more for it and what has already been built will be deleted).
set_pretty_print ($style)
Set the pretty print method, amongst 'none' (default), 'nsgmls', 'nice', 'indented', indented_c, 'wrapped', 'record' and 'record_c'
WARNING: the pretty print style is a GLOBAL variable, so once set it's applied to ALL print's (and sprint's). Same goes if you use XML::Twig with mod_perl . This should not be a problem as the XML that's generated is valid anyway, and XML processors (as well as HTML processors, including browsers) should not care. Let me know if this is a big problem, but at the moment the performance/cleanliness trade-off clearly favors the global approach.
set_empty_tag_style ($style)
Set the empty tag display style ('normal', 'html' or 'expand'). As with set_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 and expand outputs '<tag></tag>'
set_remove_cdata ($flag)
set (or unset) 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)
Return the prolog (XML declaration + DTD + entity declarations) of a document.
options: see flush.
finish
Call Expat finish method. Unsets all handlers (including internal ones that set context), but expat continues parsing to the end of the document or until it finds an error. It should finish up a lot faster than with the handlers set.
finish_print
Stop twig processing, flush the twig and proceed to finish printing the document as fast as possible. Use this method when modifying a document and the modification is done.
set_expand_external_entities
Same as using the expand_external_ents option when creating the twig
set_input_filter
Same as using the input_filter option when creating the twig
set_keep_atts_order
Same as using the keep_atts_order option when creating the twig
set_keep_encoding
Same as using the keep_encoding option when creating the twig
set_output_filter
Same as using the output_filter option when creating the twig
set_output_text_filter
Same as using the output_text_filter option when creating the twig
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. These methods can only be used during the parsing phase (they will generate a fatal error otherwise).
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 cur‐ rently opened element. If namespace processing is being used and you want to check against a name that may be in a namespace, then use the generate_ns_name method 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 the gener‐ ate_ns_name method 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 han‐ dlers, 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. LINES should be an integer >= 0 that 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. If NEWBASE is 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 cur‐ rent element. This will be zero outside of the root element. For example, this will return 1 when 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 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 by ErrorContext. Then croak with the formed message.
xpcarp
Concatenate onto the given message the current line number within the XML document plus the message implied by ErrorContext. Then carp with the formed message.
xml_escape(TEXT [, CHAR [, CHAR ...]])
Returns TEXT with markup characters turned into character entities. Any additional characters provided as arguments are also turned into character references where found in TEXT.
(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 a get_xpath on the document root (see <Elt|"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 as get_xpath
findnodes ( $optional_array_ref, $xpath, $optional_offset)
same as get_xpath (similar to the XML::LibXML method)
findvalue ( $optional_array_ref, $xpath, $optional_offset)
Return the join of all texts of the results of appling get_xpath to the node (similar to the XML::LibXML method)
subs_text ($regexp, $replace)
subs_text does text substitution on the whole document, similar to perl's s/// operator.
dispose
Useful only if you don't have Scalar::Util or WeakRef installed.
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.
create_accessors (list_of_attribute_names)
A convenience method that creates l-valued accessors for attributes. So $twig->create_accessors( 'foo') will create a foo method that can be called on elements:
$elt->foo; # equivalent to $elt->{'att'}->{'foo'};
$elt->foo( 'bar'); # equivalent to $elt->set_att( foo => 'bar');set_do_not_escape_amp_in_atts
An evil method, that I only document because Test::Pod::Coverage complaints otherwise, but really, you don't want to know about it.
XML::Twig::Elt
new ($optional_tag, $optional_atts, @optional_content)
The tag is optional (but then you can't have a content ), the $optional_atts argument is a refreference 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 strored 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 attribute 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 %args are passed to the twig. As always if the parse fails the parser will die, so use an eval if 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)
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.
sprint ($elt, $optional_no_enclosing_tag)
Return the xml string for an entire element, including the tags. If the optional second argument is true then only the string inside the element is returned (the start and end tag for $elt are not). The text is XML-escaped: base entities (& and < in text, & < and " in attribute values) are turned into entities.
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 as gi
name
Same as tag
set_gi ($tag)
Set the gi (tag) of an element
set_tag ($tag)
Set the tag (=tag) of an element