XML::Twig - A perl module for processing huge XML documents in tree mode.
Note that this documentation is intended as a reference to the module.
Complete docs, including a tutorial, examples, an easier to use HTML version, a quick reference card and a FAQ are available at http://www.xmltwig.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 document
See XML::Twig 101 for other ways to use the module, as a filter for example.
This module provides a way to process XML documents. It is build on top of XML::Parser.
The module offers a tree interface to the document, while allowing you to output the parts of it that have been completely processed.
It allows minimal resource (CPU and memory) usage by building the tree only for the parts of the documents that need actual processing, through the use of the twig_roots and twig_print_outside_roots options. The finish and finish_print methods also help to increase performances.
XML::Twig tries to make simple things easy so it tries its best to takes care of a lot of the (usually) annoying (but sometimes necessary) features that come with XML and XML::Parser.
XML::Twig can be used either on "small" XML documents (that fit in memory) or on huge ones, by processing parts of the document and outputting or discarding them once they are processed.
my $t= XML::Twig->new();
$t->parse( '<d><title>title</title><para>p 1</para><para>p 2</para></d>');
my $root= $t->root;
$root->set_tag( 'html'); # change doc to html
$title= $root->first_child( 'title'); # get the title
$title->set_tag( 'h1'); # turn it into h1
my @para= $root->children( 'para'); # get the para children
foreach my $para (@para)
{ $para->set_tag( 'p'); } # turn them into p
$t->print; # output the document
Other useful methods include:
att: $elt->{'att'}->{'foo'} return the foo attribute for an element,
set_att : $elt->set_att( foo => "bar") sets the foo attribute to the bar value,
next_sibling: $elt->{next_sibling} return the next sibling in the document (in the example $title->{next_sibling} is the first para, you can also (and actually should) use $elt->next_sibling( 'para') to get it
The document can also be transformed through the use of the cut, copy, paste and move methods: $title->cut; $title->paste( after => $p); for example
And much, much more, see Elt.
One of the strengths of XML::Twig is that it let you work with files that do not fit in memory (BTW storing an XML document in memory as a tree is quite memory-expensive, the expansion factor being often around 10).
To do this you can define handlers, that will be called once a specific element has been completely parsed. In these handlers you can access the element and process it as you see fit, using the navigation and the cut-n-paste methods, plus lots of convenient ones like prefix . Once the element is completely processed you can then flush it, which will output it and free the memory. You can also purge it if you don't need to output it (if you are just extracting some data from the document for example). The handler will be called again once the next relevant element has been parsed.
my $t= XML::Twig->new( twig_handlers =>
{ section => \§ion,
para => sub { $_->set_tag( 'p');
},
);
$t->parsefile( 'doc.xml');
$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 ,
The twig_roots mode builds only the required sub-trees from the document Anything outside of the twig roots will just be ignored:
my $t= XML::Twig->new(
# the twig will include just the root and selected titles
twig_roots => { 'section/title' => \&print_n_purge,
'annex/title' => \&print_n_purge
}
);
$t->parsefile( 'doc.xml');
sub print_n_purge
{ my( $t, $elt)= @_;
print $elt->text; # print the text (including sub-element texts)
$t->purge; # frees the memory
}
You can use that mode when you want to process parts of a documents but are not interested in the rest and you don't want to pay the price, either in time or memory, to build the tree for the it.
You can combine the twig_roots and the twig_print_outside_roots options to build filters, which let you modify selected elements and will output the rest of the document as is.
This would convert prices in $ to prices in Euro in a document:
my $t= XML::Twig->new(
twig_roots => { 'price' => \&convert, }, # process prices
twig_print_outside_roots => 1, # print the rest
);
$t->parsefile( 'doc.xml');
sub convert
{ my( $t, $price)= @_;
my $currency= $price->{'att'}->{'currency'}; # get the currency
if( $currency eq 'USD')
{ $usd_price= $price->text; # get the price
# %rate is just a conversion table
my $euro_price= $usd_price * $rate{usd2euro};
$price->set_text( $euro_price); # set the new price
$price->set_att( currency => 'EUR'); # don't forget this!
}
$price->print; # output the price
}
Before being uploaded to CPAN, XML::Twig 3.22 has been tested under the following environments:
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
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:
Note that I can't compile XML::Parser 2.27 anymore, so I can't guarantee that it still works
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
Whitespaces that look non-significant are discarded, this behaviour can be controlled using the keep_spaces , keep_spaces_in and discard_spaces_in options.
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 PI's can be hidden from the processing, but still appear in the output (they are carried by the "real" element closer to them)
XML::Twig can output the document pretty printed so it is easier to read for us humans.
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.
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.
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 dependent and might break in the future).
Other classes that are seldom used are XML::Twig::Entity_list and XML::Twig::Entity.
If you use XML::Twig::XPath instead of XML::Twig, elements are then created as XML::Twig::XPath::Elt
A twig is a subclass of XML::Parser, so all XML::Parser methods can be called on a twig object, including parse and parsefile. setHandlers on the other hand cannot be used, see BUGS
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:
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)
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, except a _all_ handler which will be called anyway.
If a handler returns a true value and other handlers apply, then the next applicable handler will be called. Repeat, rinse, lather..; The exception to that rule is when the do_not_chain_handlers option is set, in which case only the first handler will be called.
Note that it might be a good idea to explicitly return a short true value (like 1) from handlers: this ensures that other applicable handlers are called even if the last statement for the handler happens to evaluate to false. This might also speedup the code by avoiding the result of the last statement of the code to be copied and passed to the code managing handlers. It can really pay to have 1 instead of a long string returned.
When 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.
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);
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
}
}
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).
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.
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
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.
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;
}
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.
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.
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!
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
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 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
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)
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
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.
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.
Setting this option to a true value will force the twig to output CDATA sections as regular (escaped) PCDATA
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).
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.
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
Set a handler that will be called once the doctype (and the DTD) have been loaded, with 2 arguments, the twig and the DTD.
Does not output a prolog (XML declaration and DTD)
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
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.
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.
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']);
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.
Set the pretty print method, amongst 'none' (default), 'nsgmls', 'nice', 'indented', 'indented_c', 'indented_a', cvs, 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.
Note that to be totaly conformant to the "spec", the order of attributes should not be changed, so if they are not already in alphabetical order you will need to use the keep_atts_order option.
Same as idented_a.
Same as indented but a little more compact: the closing tags are on the same line as the preceding 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 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).
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
then a foo element including a bar one will be printed as
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>'
Set the quote character for attributes ('single' or 'double').
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 outputting 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.
drops the comments, they are not read, nor printed to the output
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 P