.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
. if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "XML::Generator 3pm"
.TH XML::Generator 3pm "2023-06-11" "perl v5.36.0" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
XML::Generator \- Perl extension for generating XML
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 1
\& use XML::Generator \*(Aq:pretty\*(Aq;
\&
\& print foo(bar({ baz => 3 }, bam()),
\& bar([ \*(Aqqux\*(Aq => \*(Aqhttp://qux.com/\*(Aq ],
\& "Hey there, world"));
\&
\& # OR
\&
\& require XML::Generator;
\&
\& my $X = XML::Generator\->new(\*(Aq:pretty\*(Aq);
\&
\& print $X\->foo($X\->bar({ baz => 3 }, $X\->bam()),
\& $X\->bar([ \*(Aqqux\*(Aq => \*(Aqhttp://qux.com/\*(Aq ],
\& "Hey there, world"));
.Ve
.PP
Either of the above yield:
.PP
.Vb 6
\&
\&
\&
\&
\& Hey there, world
\&
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
In general, once you have an XML::Generator object, you then simply call
methods on that object named for each \s-1XML\s0 tag you wish to generate.
.PP
XML::Generator can also arrange for undefined subroutines in the caller's
package to generate the corresponding \s-1XML,\s0 by exporting an \f(CW\*(C`AUTOLOAD\*(C'\fR
subroutine to your package. Just supply an ':import' argument to
your \f(CW\*(C`use XML::Generator;\*(C'\fR call. If you already have an \f(CW\*(C`AUTOLOAD\*(C'\fR
defined then XML::Generator can be configured to cooperate with it.
See \*(L"\s-1STACKABLE\s0 AUTOLOADs\*(R".
.PP
Say you want to generate this \s-1XML:\s0
.PP
.Vb 5
\&
\& Bob
\& 34
\& Accountant
\&
.Ve
.PP
Here's a snippet of code that does the job, complete with pretty printing:
.PP
.Vb 7
\& use XML::Generator;
\& my $gen = XML::Generator\->new(\*(Aq:pretty\*(Aq);
\& print $gen\->person(
\& $gen\->name("Bob"),
\& $gen\->age(34),
\& $gen\->job("Accountant")
\& );
.Ve
.PP
The only problem with this is if you want to use a tag name that
Perl's lexer won't understand as a method name, such as \*(L"shoe-size\*(R".
Fortunately, since you can store the name of a method in a variable,
there's a simple work-around:
.PP
.Vb 2
\& my $shoe_size = "shoe\-size";
\& $xml = $gen\->$shoe_size("12 1/2");
.Ve
.PP
Which correctly generates:
.PP
.Vb 1
\& 12 1/2
.Ve
.PP
You can use a hash ref as the first parameter if the tag should include
atributes. Normally this means that the order of the attributes will be
unpredictable, but if you have the Tie::IxHash module, you can use it
to get the order you want, like this:
.PP
.Vb 2
\& use Tie::IxHash;
\& tie my %attr, \*(AqTie::IxHash\*(Aq;
\&
\& %attr = (name => \*(AqBob\*(Aq,
\& age => 34,
\& job => \*(AqAccountant\*(Aq,
\& \*(Aqshoe\-size\*(Aq => \*(Aq12 1/2\*(Aq);
\&
\& print $gen\->person(\e%attr);
.Ve
.PP
This produces
.PP
.Vb 1
\&
.Ve
.PP
An array ref can also be supplied as the first argument to indicate
a namespace for the element and the attributes.
.PP
If there is one element in the array, it is considered the \s-1URI\s0 of
the default namespace, and the tag will have an xmlns=\*(L"\s-1URI\*(R"\s0 attribute
added automatically. If there are two elements, the first should be
the tag prefix to use for the namespace and the second element should
be the \s-1URI.\s0 In this case, the prefix will be used for the tag and an
xmlns:PREFIX attribute will be automatically added. Prior to version
0.99, this prefix was also automatically added to each attribute name.
Now, the default behavior is to leave the attributes alone (although you
may always explicitly add a prefix to an attribute name). If the prior
behavior is desired, use the constructor option \f(CW\*(C`qualified_attributes\*(C'\fR.
.PP
If you specify more than two elements, then each pair should correspond
to a tag prefix and the corresponding \s-1URL.\s0 An xmlns:PREFIX attribute
will be added for each pair, and the prefix from the first such pair
will be used as the tag's namespace. If you wish to specify a default
namespace, use '#default' for the prefix. If the default namespace is
first, then the tag will use the default namespace itself.
.PP
If you want to specify a namespace as well as attributes, you can make
the second argument a hash ref. If you do it the other way around,
the array ref will simply get stringified and included as part of the
content of the tag.
.PP
Here's an example to show how the attribute and namespace parameters work:
.PP
.Vb 4
\& $xml = $gen\->account(
\& $gen\->open([\*(Aqtransaction\*(Aq], 2000),
\& $gen\->deposit([\*(Aqtransaction\*(Aq], { date => \*(Aq1999.04.03\*(Aq}, 1500)
\& );
.Ve
.PP
This generates:
.PP
.Vb 4
\&
\& 2000
\& 1500
\&
.Ve
.PP
Because default namespaces inherit, XML::Generator takes care to output
the xmlns=\*(L"\s-1URI\*(R"\s0 attribute as few times as strictly necessary. For example,
.PP
.Vb 6
\& $xml = $gen\->account(
\& $gen\->open([\*(Aqtransaction\*(Aq], 2000),
\& $gen\->deposit([\*(Aqtransaction\*(Aq], { date => \*(Aq1999.04.03\*(Aq},
\& $gen\->amount([\*(Aqtransaction\*(Aq], 1500)
\& )
\& );
.Ve
.PP
This generates:
.PP
.Vb 6
\&
\& 2000
\&
\& 1500
\&
\&
.Ve
.PP
Notice how \f(CW\*(C`xmlns="transaction"\*(C'\fR was left out of the \f(CW\*(C` tag.
.PP
Here is an example that uses the two-argument form of the namespace:
.PP
.Vb 2
\& $xml = $gen\->widget([\*(Aqwru\*(Aq => \*(Aqhttp://www.widgets\-r\-us.com/xml/\*(Aq],
\& {\*(Aqid\*(Aq => 123}, $gen\->contents());
\&
\&
\&
\&
.Ve
.PP
Here is an example that uses multiple namespaces. It generates the
first example from the \s-1RDF\s0 primer ().
.PP
.Vb 8
\& my $contactNS = [contact => "http://www.w3.org/2000/10/swap/pim/contact#"];
\& $xml = $gen\->xml(
\& $gen\->RDF([ rdf => "http://www.w3.org/1999/02/22\-rdf\-syntax\-ns#",
\& @$contactNS ],
\& $gen\->Person($contactNS, { \*(Aqrdf:about\*(Aq => "http://www.w3.org/People/EM/contact#me" },
\& $gen\->fullName($contactNS, \*(AqEric Miller\*(Aq),
\& $gen\->mailbox($contactNS, {\*(Aqrdf:resource\*(Aq => "mailto:em@w3.org"}),
\& $gen\->personalTitle($contactNS, \*(AqDr.\*(Aq))));
\&
\&
\&
\&
\& Eric Miller
\&
\& Dr.
\&
\&
.Ve
.SH "CONSTRUCTOR"
.IX Header "CONSTRUCTOR"
XML::Generator\->new(':option', ...);
.PP
XML::Generator\->new(option => 'value', ...);
.PP
(Both styles may be combined)
.PP
The following options are available:
.SS ":std, :standard"
.IX Subsection ":std, :standard"
Equivalent to
.PP
.Vb 2
\& escape => \*(Aqalways\*(Aq,
\& conformance => \*(Aqstrict\*(Aq,
.Ve
.SS ":strict"
.IX Subsection ":strict"
Equivalent to
.PP
.Vb 1
\& conformance => \*(Aqstrict\*(Aq,
.Ve
.SS ":pretty[=N]"
.IX Subsection ":pretty[=N]"
Equivalent to
.PP
.Vb 3
\& escape => \*(Aqalways\*(Aq,
\& conformance => \*(Aqstrict\*(Aq,
\& pretty => N # N defaults to 2
.Ve
.SS "namespace"
.IX Subsection "namespace"
This value of this option must be an array reference containing one or
two values. If the array contains one value, it should be a \s-1URI\s0 and will
be the value of an 'xmlns' attribute in the top-level tag. If there are
two or more elements, the first of each pair should be the namespace
tag prefix and the second the \s-1URI\s0 of the namespace. This will enable
behavior similar to the namespace behavior in previous versions; the tag
prefix will be applied to each tag. In addition, an xmlns:NAME=\*(L"\s-1URI\*(R"\s0
attribute will be added to the top-level tag. Prior to version 0.99,
the tag prefix was also automatically added to each attribute name,
unless overridden with an explicit prefix. Now, the attribute names are
left alone, but if the prior behavior is desired, use the constructor
option \f(CW\*(C`qualified_attributes\*(C'\fR.
.PP
The value of this option is used as the global default namespace.
For example,
.PP
.Vb 7
\& my $html = XML::Generator\->new(
\& pretty => 2,
\& namespace => [HTML => "http://www.w3.org/TR/REC\-html40"]);
\& print $html\->html(
\& $html\->body(
\& $html\->font({ face => \*(AqArial\*(Aq },
\& "Hello, there")));
.Ve
.PP
would yield
.PP
.Vb 5
\&
\&
\& Hello, there
\&
\&
.Ve
.PP
Here is the same example except without all the prefixes:
.PP
.Vb 7
\& my $html = XML::Generator\->new(
\& pretty => 2,
\& namespace => ["http://www.w3.org/TR/REC\-html40"]);
\& print $html\->html(
\& $html\->body(
\& $html\->font({ \*(Aqface\*(Aq => \*(AqArial\*(Aq },
\& "Hello, there")));
.Ve
.PP
would yield
.PP
.Vb 5
\&
\&
\& Hello, there
\&
\&
.Ve
.SS "qualifiedAttributes, qualified_attributes"
.IX Subsection "qualifiedAttributes, qualified_attributes"
Set this to a true value to emulate the attribute prefixing behavior of
XML::Generator prior to version 0.99. Here is an example:
.PP
.Vb 4
\& my $foo = XML::Generator\->new(
\& namespace => [foo => "http://foo.com/"],
\& qualifiedAttributes => 1);
\& print $foo\->bar({baz => 3});
.Ve
.PP
yields
.PP
.Vb 1
\&
.Ve
.SS "escape"
.IX Subsection "escape"
The contents and the values of each attribute have any illegal \s-1XML\s0
characters escaped if this option is supplied. If the value is 'always',
then &, < and > (and " within attribute values) will be converted into
the corresponding \s-1XML\s0 entity, although & will not be converted if it looks
like it could be part of a valid entity (but see below). If the value is
\&'unescaped', then the escaping will be turned off character-by-character
if the character in question is preceded by a backslash, or for the
entire string if it is supplied as a scalar reference. So, for example,
.PP
.Vb 1
\& use XML::Generator escape => \*(Aqalways\*(Aq;
\&
\& one(\*(Aq<\*(Aq); # <
\& two(\*(Aq\e&\*(Aq); # \e&
\& three(\e\*(Aq\*(Aq); # (scalar refs always allowed)
\& four(\*(Aq<\*(Aq); # < (looks like an entity)
\& five(\*(Aq"\*(Aq); # " (looks like an entity)
.Ve
.PP
but
.PP
.Vb 1
\& use XML::Generator escape => \*(Aqunescaped\*(Aq;
\&
\& one(\*(Aq<\*(Aq); # <
\& two(\*(Aq\e&\*(Aq); # &
\& three(\e\*(Aq\*(Aq);# (scalar refs always allowed)
\& four(\*(Aq<\*(Aq); # < (no special case for entities)
.Ve
.PP
By default, high-bit data will be passed through unmodified, so that
\&\s-1UTF\-8\s0 data can be generated with pre-Unicode perls. If you know that
your data is \s-1ASCII,\s0 use the value 'high\-bit' for the escape option
and bytes with the high bit set will be turned into numeric entities.
You can combine this functionality with the other escape options by
comma-separating the values:
.PP
.Vb 2
\& my $a = XML::Generator\->new(escape => \*(Aqalways,high\-bit\*(Aq);
\& print $a\->foo("<\e242>");
.Ve
.PP
yields
.PP
.Vb 1
\& <¢>
.Ve
.PP
Because XML::Generator always uses double quotes ("") around attribute
values, it does not escape single quotes. If you want single quotes
inside attribute values to be escaped, use the value 'apos' along with
\&'always' or 'unescaped' for the escape option. For example:
.PP
.Vb 2
\& my $gen = XML::Generator\->new(escape => \*(Aqalways,apos\*(Aq);
\& print $gen\->foo({\*(Aqbar\*(Aq => "It\*(Aqs all good"});
\&
\&
.Ve
.PP
If you actually want & to be converted to & even if it looks like it
could be part of a valid entity, use the value 'even\-entities' along with
\&'always'. Supplying 'even\-entities' to the 'unescaped' option is meaningless
as entities are already escaped with that option.
.SS "pretty"
.IX Subsection "pretty"
To have nice pretty printing of the output \s-1XML\s0 (great for config files
that you might also want to edit by hand), supply an integer for the
number of spaces per level of indenting, eg.
.PP
.Vb 3
\& my $gen = XML::Generator\->new(pretty => 2);
\& print $gen\->foo($gen\->bar(\*(Aqbaz\*(Aq),
\& $gen\->qux({ tricky => \*(Aqno\*(Aq}, \*(Aqquux\*(Aq));
.Ve
.PP
would yield
.PP
.Vb 4
\&
\& baz
\& quux
\&
.Ve
.PP
You may also supply a non-numeric string as the argument to 'pretty', in
which case the indents will consist of repetitions of that string. So if
you want tabbed indents, you would use:
.PP
.Vb 1
\& my $gen = XML::Generator\->new(pretty => "\et");
.Ve
.PP
Pretty printing does not apply to \s-1CDATA\s0 sections or Processing Instructions.
.SS "conformance"
.IX Subsection "conformance"
If the value of this option is 'strict', a number of syntactic
checks are performed to ensure that generated \s-1XML\s0 conforms to the
formal \s-1XML\s0 specification. In addition, since entity names beginning
with 'xml' are reserved by the W3C, inclusion of this option enables
several special tag names: xmlpi, xmlcmnt, xmldecl, xmldtd, xmlcdata,
and xml to allow generation of processing instructions, comments, \s-1XML\s0
declarations, \s-1DTD\s0's, character data sections and \*(L"final\*(R" \s-1XML\s0 documents,
respectively.
.PP
Invalid characters (http://www.w3.org/TR/xml11/#charsets) will be filtered
out. To disable this behavior, supply the 'filter_invalid_chars' option with
the value 0.
.PP
See \*(L"\s-1XML CONFORMANCE\*(R"\s0 and \*(L"\s-1SPECIAL TAGS\*(R"\s0 for more information.
.SS "filterInvalidChars, filter_invalid_chars"
.IX Subsection "filterInvalidChars, filter_invalid_chars"
Set this to a 1 to enable filtering of invalid characters, or to 0 to disable
the filtering. See http://www.w3.org/TR/xml11/#charsets for the set of valid
characters.
.SS "allowedXMLTags, allowed_xml_tags"
.IX Subsection "allowedXMLTags, allowed_xml_tags"
If you have specified 'conformance' => 'strict' but need to use tags
that start with 'xml', you can supply a reference to an array containing
those tags and they will be accepted without error. It is not an error
to supply this option if 'conformance' => 'strict' is not supplied,
but it will have no effect.
.SS "empty"
.IX Subsection "empty"
There are 5 possible values for this option:
.PP
.Vb 5
\& self \- create empty tags as (default)
\& compact \- create empty tags as
\& close \- close empty tags as
\& ignore \- don\*(Aqt do anything (non\-compliant!)
\& args \- use count of arguments to decide between and
.Ve
.PP
Many web browsers like the 'self' form, but any one of the forms besides
\&'ignore' is acceptable under the \s-1XML\s0 standard.
.PP
\&'ignore' is intended for subclasses that deal with \s-1HTML\s0 and other
\&\s-1SGML\s0 subsets which allow atomic tags. It is an error to specify both
\&'conformance' => 'strict' and 'empty' => 'ignore'.
.PP
\&'args' will produce if there are no arguments at all, or if there
is just a single undef argument, and otherwise.
.SS "version"
.IX Subsection "version"
Sets the default \s-1XML\s0 version for use in \s-1XML\s0 declarations.
See \*(L"xmldecl\*(R" below.
.SS "encoding"
.IX Subsection "encoding"
Sets the default encoding for use in \s-1XML\s0 declarations.
.SS "dtd"
.IX Subsection "dtd"
Specify the dtd. The value should be an array reference with three
values; the type, the name and the uri.
.SS "xml"
.IX Subsection "xml"
This is an hash ref value that should contain the version, encoding and dtd
values (same as above). This is used in case \f(CW\*(C`conformance\*(C'\fR is set to \f(CW\*(C`loose\*(C'\fR,
but you still want to use the xml declaration or prolog.
.SH "IMPORT ARGUMENTS"
.IX Header "IMPORT ARGUMENTS"
use XML::Generator ':option';
.PP
use XML::Generator option => 'value';
.PP
(Both styles may be combined)
.SS ":import"
.IX Subsection ":import"
Cause \f(CW\*(C`use XML::Generator;\*(C'\fR to export an \f(CW\*(C`AUTOLOAD\*(C'\fR to your package that
makes undefined subroutines generate \s-1XML\s0 tags corresponding to their name.
Note that if you already have an \f(CW\*(C`AUTOLOAD\*(C'\fR defined, it will be overwritten.
.SS ":stacked"
.IX Subsection ":stacked"
Implies :import, but if there is already an \f(CW\*(C`AUTOLOAD\*(C'\fR defined, the
overriding \f(CW\*(C`AUTOLOAD\*(C'\fR will still give it a chance to run. See \*(L"\s-1STACKABLE\s0
AUTOLOADs\*(R".
.SS "\s-1ANYTHING ELSE\s0"
.IX Subsection "ANYTHING ELSE"
If you supply any other options, :import is implied and the XML::Generator
object that is created to generate tags will be constructed with those options.
.SH "XML CONFORMANCE"
.IX Header "XML CONFORMANCE"
When the 'conformance' => 'strict' option is supplied, a number of
syntactic checks are enabled. All entity and attribute names are
checked to conform to the \s-1XML\s0 specification, which states that they must
begin with either an alphabetic character or an underscore and may then
consist of any number of alphanumerics, underscores, periods or hyphens.
Alphabetic and alphanumeric are interpreted according to the current
locale if 'use locale' is in effect and according to the Unicode standard
for Perl versions >= 5.6. Furthermore, entity or attribute names are not
allowed to begin with 'xml' (in any case), although a number of special
tags beginning with 'xml' are allowed (see \*(L"\s-1SPECIAL TAGS\*(R"\s0). Note
that you can also supply an explicit list of allowed tags with the
\&'allowed_xml_tags' option.
.PP
Also, the filter_invalid_chars option is automatically set to 1 unless it
is explicitly set to 0.
.SH "SPECIAL TAGS"
.IX Header "SPECIAL TAGS"
The following special tags are available when running under strict
conformance (otherwise they don't act special):
.SS "xmlpi"
.IX Subsection "xmlpi"
Processing instruction; first argument is target, remaining arguments
are attribute, value pairs. Attribute names are syntax checked, values
are escaped.
.SS "xmlcmnt"
.IX Subsection "xmlcmnt"
Comment. Arguments are concatenated and placed inside
comment delimiters. Any occurences of '\-\-' in the concatenated arguments
are converted to '--'
.SS "xmldecl (@args)"
.IX Subsection "xmldecl (@args)"
Declaration. This can be used to specify the version, encoding, and
other XML-related declarations (i.e., anything inside the tag).
\&\f(CW@args\fR can be used to control what is output, as keyword-value pairs.
.PP
By default, the version is set to the value specified in the constructor,
or to 1.0 if it was not specified. This can be overridden by providing a
\&'version' key in \f(CW@args\fR. If you do not want the version at all, explicitly
provide undef as the value in \f(CW@args\fR.
.PP
By default, the encoding is set to the value specified in the constructor;
if no value was specified, the encoding will be left out altogether.
Provide an 'encoding' key in \f(CW@args\fR to override this.
.PP
If a dtd was set in the constructor, the standalone attribute of the
declaration will be set to 'no' and the doctype declaration will be
appended to the \s-1XML\s0 declartion, otherwise the standalone attribute will
be set to 'yes'. This can be overridden by providing a 'standalone'
key in \f(CW@args\fR. If you do not want the standalone attribute to show up,
explicitly provide undef as the value.
.SS "xmldtd"
.IX Subsection "xmldtd"
\&\s-1DTD\s0 tag creation. The format of this method is different from
others. Since \s-1DTD\s0's are global and cannot contain namespace information,
the first argument should be a reference to an array; the elements are
concatenated together to form the \s-1DTD:\s0
.PP
.Vb 1
\& print $xml\->xmldtd([ \*(Aqhtml\*(Aq, \*(AqPUBLIC\*(Aq, $xhtml_w3c, $xhtml_dtd ])
.Ve
.PP
This would produce the following declaration:
.PP
.Vb 2
\&
.Ve
.PP
Assuming that \f(CW$xhtml_w3c\fR and \f(CW$xhtml_dtd\fR had the correct values.
.PP
Note that you can also specify a \s-1DTD\s0 on creation using the \fBnew()\fR method's
dtd option.
.SS "xmlcdata"
.IX Subsection "xmlcdata"
Character data section; arguments are concatenated and placed inside
character data section delimiters. Any occurences of
\&']]>' in the concatenated arguments are converted to ']]>'.
.SS "xml"
.IX Subsection "xml"
\&\*(L"Final\*(R" \s-1XML\s0 document. Must be called with one and exactly one
XML::Generator\-produced \s-1XML\s0 document. Any combination of
XML::Generator\-produced \s-1XML\s0 comments or processing instructions may
also be supplied as arguments. Prepends an \s-1XML\s0 declaration, and
re-blesses the argument into a \*(L"final\*(R" class that can't be embedded.
.SH "CREATING A SUBCLASS"
.IX Header "CREATING A SUBCLASS"
For a simpler way to implement subclass-like behavior, see \*(L"\s-1STACKABLE\s0
AUTOLOADs\*(R".
.PP
At times, you may find it desireable to subclass XML::Generator. For
example, you might want to provide a more application-specific interface
to the \s-1XML\s0 generation routines provided. Perhaps you have a custom
database application and would really like to say:
.PP
.Vb 2
\& my $dbxml = new XML::Generator::MyDatabaseApp;
\& print $dbxml\->xml($dbxml\->custom_tag_handler(@data));
.Ve
.PP
Here, \fBcustom_tag_handler()\fR may be a method that builds a recursive \s-1XML\s0
structure based on the contents of \f(CW@data\fR. In fact, it may even be named
for a tag you want generated, such as \fBauthors()\fR, whose behavior changes
based on the contents (perhaps creating recursive definitions in the
case of multiple elements).
.PP
Creating a subclass of XML::Generator is actually relatively
straightforward, there are just three things you have to remember:
.PP
.Vb 1
\& 1. All of the useful utilities are in XML::Generator::util.
\&
\& 2. To construct a tag you simply have to call SUPER::tagname,
\& where "tagname" is the name of your tag.
\&
\& 3. You must fully\-qualify the methods in XML::Generator::util.
.Ve
.PP
So, let's assume that we want to provide a custom \s-1HTML\s0 \fBtable()\fR method:
.PP
.Vb 2
\& package XML::Generator::CustomHTML;
\& use base \*(AqXML::Generator\*(Aq;
\&
\& sub table {
\& my $self = shift;
\&
\& # parse our args to get namespace and attribute info
\& my($namespace, $attr, @content) =
\& $self\->XML::Generator::util::parse_args(@_)
\&
\& # check for strict conformance
\& if ( $self\->XML::Generator::util::config(\*(Aqconformance\*(Aq) eq \*(Aqstrict\*(Aq ) {
\& # ... special checks ...
\& }
\&
\& # ... special formatting magic happens ...
\&
\& # construct our custom tags
\& return $self\->SUPER::table($attr, $self\->tr($self\->td(@content)));
\& }
.Ve
.PP
That's pretty much all there is to it. We have to explicitly call
\&\fBSUPER::table()\fR since we're inside the class's \fBtable()\fR method. The others
can simply be called directly, assuming that we don't have a \fBtr()\fR in the
current package.
.PP
If you want to explicitly create a specific tag by name, or just want a
faster approach than \s-1AUTOLOAD\s0 provides, you can use the \fBtag()\fR method
directly. So, we could replace that last line above with:
.PP
.Vb 2
\& # construct our custom tags
\& return $self\->XML::Generator::util::tag(\*(Aqtable\*(Aq, $attr, ...);
.Ve
.PP
Here, we must explicitly call \fBtag()\fR with the tag name itself as its first
argument so it knows what to generate. These are the methods that you might
find useful:
.IP "\fBXML::Generator::util::parse_args()\fR" 4
.IX Item "XML::Generator::util::parse_args()"
This parses the argument list and returns the namespace (arrayref), attributes
(hashref), and remaining content (array), in that order.
.IP "\fBXML::Generator::util::tag()\fR" 4
.IX Item "XML::Generator::util::tag()"
This does the work of generating the appropriate tag. The first argument must
be the name of the tag to generate.
.IP "\fBXML::Generator::util::config()\fR" 4
.IX Item "XML::Generator::util::config()"
This retrieves options as set via the \fBnew()\fR method.
.IP "\fBXML::Generator::util::escape()\fR" 4
.IX Item "XML::Generator::util::escape()"
This escapes any illegal \s-1XML\s0 characters.
.PP
Remember that all of these methods must be fully-qualified with the
XML::Generator::util package name. This is because \s-1AUTOLOAD\s0 is used by
the main XML::Generator package to create tags. Simply calling \fBparse_args()\fR
will result in a set of \s-1XML\s0 tags called .
.PP
Finally, remember that since you are subclassing XML::Generator, you do
not need to provide your own \fBnew()\fR method. The one from XML::Generator
is designed to allow you to properly subclass it.
.SH "STACKABLE AUTOLOADs"
.IX Header "STACKABLE AUTOLOADs"
As a simpler alternative to traditional subclassing, the \f(CW\*(C`AUTOLOAD\*(C'\fR
that \f(CW\*(C`use XML::Generator;\*(C'\fR exports can be configured to work with a
pre-defined \f(CW\*(C`AUTOLOAD\*(C'\fR with the ':stacked' option. Simply ensure that
your \f(CW\*(C`AUTOLOAD\*(C'\fR is defined before \f(CW\*(C`use XML::Generator \*(Aq:stacked\*(Aq;\*(C'\fR
executes. The \f(CW\*(C`AUTOLOAD\*(C'\fR will get a chance to run first; the subroutine
name will be in your \f(CW$AUTOLOAD\fR as normal. Return an empty list to let
the default XML::Generator \f(CW\*(C`AUTOLOAD\*(C'\fR run or any other value to abort it.
This value will be returned as the result of the original method call.
.PP
If there is no \f(CW\*(C`import\*(C'\fR defined, XML::Generator will create one.
All that this \f(CW\*(C`import\*(C'\fR does is export \s-1AUTOLOAD,\s0 but that lets your
package be used as if it were a subclass of XML::Generator.
.PP
An example will help:
.PP
.Vb 1
\& package MyGenerator;
\&
\& my %entities = ( copy => \*(Aq©\*(Aq,
\& nbsp => \*(Aq \*(Aq, ... );
\&
\& sub AUTOLOAD {
\& my($tag) = our $AUTOLOAD =~ /.*::(.*)/;
\&
\& return $entities{$tag} if defined $entities{$tag};
\& return;
\& }
\&
\& use XML::Generator qw(:pretty :stacked);
.Ve
.PP
This lets someone do:
.PP
.Vb 1
\& use MyGenerator;
\&
\& print html(head(title("My Title", copy())));
.Ve
.PP
Producing:
.PP
.Vb 5
\&
\&
\& My Title©
\&
\&
.Ve
.SH "AUTHORS"
.IX Header "AUTHORS"
.IP "Benjamin Holzman " 4
.IX Item "Benjamin Holzman "
Original author and maintainer
.IP "Bron Gondwana " 4
.IX Item "Bron Gondwana "
First modular version
.IP "Nathan Wiger " 4
.IX Item "Nathan Wiger "
Modular rewrite to enable subclassing
.SH "LICENSE"
.IX Header "LICENSE"
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
.IP "The XML::Writer module" 4
.IX Item "The XML::Writer module"
http://search.cpan.org/search?mode=module&query=XML::Writer