generator(3)

NAME

XML::Generator - Perl extension for generating XML

SYNOPSIS

use XML::Generator;
my $xml = XML::Generator->new(escape => 'always',
                              pretty => 2,
                              conformance => 'strict');
print $xml->foo($xml->bar({ baz => 3 }, $xml->bam),
                $xml->bar([   'qux'   ],   "Hey  there,
world"));
# The above would yield:
<foo>
  <bar baz="3">
    <bam />
  </bar>
  <qux:bar>Hey there, world</qux:bar>
</foo>

DESCRIPTION

In general, once you have an XML::Generator object, you
then simply call methods on that object named for each XML
tag you wish to generate. Say you want to generate this
XML:
<person>
<name>Bob</name>
<age>34</age>
<job>Accountant</job>
</person>
Here's a snippet of code that does the job, complete with
pretty printing:

use XML::Generator;
my $gen = XML::Generator->new(escape => 'always', pret
ty => 2);
print $gen->person(
$gen->name("Bob"),
$gen->age(34),
$gen->job("Accountant")
);
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 "shoe-size". Fortunately, since you can always
call methods as variable names, there's a simple
work-around:

my $shoe_size = "shoe-size";
$xml = $gen->$shoe_size("12 1/2");
Which correctly generates:

<shoe-size>12 1/2</shoe-size>
You can use a hash ref as the first parameter if the tag
should include atributes. An array ref can be supplied as
the first argument to indicate a namespace for the element
and the attributes (the elements of the array are concate
nated with ':'). Under strict conformance, however, you
are only allowed one namespace component.
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. If an XML::Generator object has a namespace set, and
a namespace is also supplied to the tag, the supplied
namespace overrides the default.
Here's an example to show how the attribute and namespace
parameters work:

$xml = $gen->account({ type => 'checking', id =>
'34758'},
$gen->open(['transaction'], 2000),
$gen->deposit(['transaction'], { date =>
'1999.04.03'}, 1500)
);
This generates:

<account type="checking" id="34578">
<transaction:open>2000</transaction:open>
<transaction:deposit transac
tion:date="1999.04.03">1500</transaction:deposit>
</account>

CONSTRUCTOR

XML::Generator->new(option => 'value', option => 'value');

The following options are available:

namespace

The value of this option is used as the global default
namespace. For example,
my $html = XML::Generator->new(namespace => 'HTML');
print $html->font({ face => 'Arial' }, "Hello, there");
would yield

<HTML:font HTML:face="Arial">Hello, there</HTML:font>
See HTML::Generator for routines specific to HTML genera
tion.
escape
The contents and the values of each attribute have any
illegal XML characters escaped if this option is supplied.
If the value is 'always', then &, < and > (and " within
attribute values) will be converted into the corresponding
XML entity. If the value is any other true value, 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 refer
ence. So, for example,

my $a = XML::Generator->new(escape => 'always');
my $b = XML::Generator->new(escape => 'true');
print $a->foo('<', $b->bar('3 > 4',
would yield

<foo>&lt;<bar>3 > 4 && 6 < 5</bar>amp;&gt;</foo>
pretty
To have nice pretty printing of the output XML (great for
config files that you might also want to edit by hand),
pass an integer for the number of spaces per level of
indenting, eg.

my $gen = XML::Generator->new(pretty => 2);
print $gen->foo($gen->bar('baz'),
$gen->qux({ tricky => 'no'}, 'quux'));
would yield

<foo>
<bar>baz</bar>
<qux tricky="no">quux</qux>
</foo>
Pretty printing does not apply to CDATA sections or Pro
cessing Instructions.
conformance
If the value of this option is 'strict', a number of syn
tactic checks are performed to ensure that generated XML
conforms to the formal XML 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, com
ments, XML declarations, DTD's, character data sections
and "final" XML documents, respectively.
See "XML CONFORMANCE" and "SPECIAL TAGS" for more informa
tion.
empty
There are 5 possible values for this option:

self - create empty tags as <tag /> (default)
compact - create empty tags as <tag/>
close - close empty tags as <tag></tag>
ignore - don't do anything (non-compliant!)
args - use count of arguments to decide between <x
/> and <x></x>
Many web browsers like the 'self' form, but any one of the
forms besides 'ignore' is acceptable under the XML stan
dard.
'ignore' is intended for subclasses that deal with HTML
and other SGML subsets which allow atomic tags. It is an
error to specify both 'conformance' => 'strict' and
'empty' => 'ignore'.
'args' will produce <x /> if there are no arguments at
all, or if there is just a single undef argument, and
<x></x> otherwise.

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 XML specifi
cation, 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 ver
sions >= 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 "SPECIAL TAGS").

In addition, only one namespace component will be allowed
when strict conformance is in effect, and attribute names
can be given a specific namespace, which will override
both the default namespace and the tag- specific names
pace. For example,
my $gen = XML::Generator->new(conformance => 'strict',
namespace => 'foo');
my $xml = $gen->bar({ a => 1 },
$gen->baz(['bam'], { b => 2, 'name:c' => 3
})
);
will generate:

<foo:bar foo:a="1"><bam:baz bam:b="2" name:c="3"
/></foo:bar>

SPECIAL TAGS

The following special tags are available when running
under strict conformance (otherwise they don't act spe
cial):

xmlpi

Processing instruction; first argument is target, remain
ing arguments are attribute, value pairs. Attribute names
are syntax checked, values are escaped.

xmlcmnt

Comment. Arguments are concatenated and placed inside
<!-- ... --> comment delimiters. Any occurences of '--'
in the concatenated arguments are converted to '-&#45;'

xmldecl

Declaration. This can be used to specify the version,
encoding, and other XML-related declarations (i.e., any
thing inside the <?xml?> tag).

xmldtd

DTD <!DOCTYPE> tag creation. The format of this method is
different from others. Since DTD's are global and cannot
contain namespace information, the first argument arrayref
is concatenated together to form the DTD:
print $xml->xmldtd([ 'html', 'PUBLIC', $xhtml_w3c,
$xhtml_dtd ])
This would produce the following declaration:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi
tional//EN"
"DTD/xhtml1-transitional.dtd">
Assuming that $xhtml_w3c and $xhtml_dtd had the correct
values. For shortcuts to <!DOCTYPE> generation, see the
HTML::Generator module. Note that you can also specify a
DTD on creation using the new() method's dtd option.
xmlcdata
Character data section; arguments are concatenated and
placed inside <![CDATA[ ... ]]> character data section
delimiters. Any occurences of ']]>' in the concatenated
arguments are converted to ']]&gt;'.
xml
"Final" XML document. Must be called with one and exactly
one XML::Generator-produced XML document. Any combination
of XML::Generator-produced XML comments or processing
instructions may also be supplied as arguments. Prepends
an XML declaration, and re-blesses the argument into a
"final" class that can't be embedded.

CREATING A SUBCLASS

For an example of how to subclass XML::Generator, see
Nathan Wiger's HTML::Generator module.

At times, you may find it desireable to subclass XML::Gen
erator. For example, you might want to provide a more
application-specific interface to the XML generation rou
tines provided. Perhaps you have a custom database appli
cation and would really like to say:
my $dbxml = new XML::Generator::MyDatabaseApp;
print $dbxml->xml($dbxml->custom_tag_handler(@data));
Here, custom_tag_handler() may be a method that builds a recursive XML structure based on the contents of @data. In
fact, it may even be named for a tag you want generated,
such as authors(), whose behavior changes based on the contents (perhaps creating recursive definitions in the
case of multiple elements).
Creating a subclass of XML::Generator is actually rela
tively straightforward, there are just three things you
have to remember:

1. All of the useful utilities are in XML::Genera
tor::util.
2. To construct a tag you simply have to call SU
PER::tagname,
where "tagname" is the name of your tag.
3. You must fully-qualify the methods in XML::Genera
tor::util.
So, let's assume that we want to provide a custom HTML
table() method:

package XML::Generator::CustomHTML;
use base 'XML::Generator';
sub table {
my $self = shift;
# parse our args to get namespace and attribute in
fo
my($namespace, $attr, @content) =
$self->XML::Generator::util::parse_args(@_)
# check for strict conformance
if ( $self->XML::Generator::util::config('confor
mance') eq 'strict' ) {
# ... special checks ...
}
# ... special formatting magic happens ...
# construct our custom tags
return $self->SUPER::table($attr,
$self->tr($self->td(@content)));
}
That's pretty much all there is to it. We have to explic
itly call SUPER::table() since we're inside the class's table() method. The others can simply be called directly, assuming that we don't have a tr() in the current package.
If you want to explicitly create a specific tag by name,
or just want a faster approach than AUTOLOAD provides, you
can use the tag() method directly. So, we could replace
that last line above with:

# construct our custom tags
return $self->XML::Generator::util::tag('table',
$attr, ...);
Here, we must explicitly call tag() with the tag name
itself as its first argument so it knows what to generate.
These are the methods that you might find useful:
XML::Generator::util::parse_args() This parses the argument list and returns the names
pace (arrayref), attributes (hashref), and remaining
content (array), in that order.
XML::Generator::util::tag() This does the work of generating the appropriate tag.
The first argument must be the name of the tag to gen
erate.
XML::Generator::util::config() This retrieves options as set via the new() method.
XML::Generator::util::escape() This escapes any illegal XML characters.
Remember that all of these methods must be fully-qualified
with the XML::Generator::util package name. This is
because AUTOLOAD is used by the main XML::Generator pack
age to create tags. Simply calling parse_args() will result in a set of XML tags called <parse_args>.
Finally, remember that since you are subclassing XML::Gen
erator, you do not need to provide your own new() method.
The one from XML::Generator is designed to allow you to
properly subclass it.

AUTHORS

Benjamin Holzman <bholzman@earthlink.net>
Original author and maintainer
Bron Gondwana <perlcode@brong.net>
First modular version
Nathan Wiger <nate@nateware.com>
Modular rewrite to enable subclassing

SEE ALSO

Perl-XML FAQ
http://www.perlxml.com/faq/perl-xml-faq.html
The XML::Writer modulehttp://search.cpan.org/search?mode=mod
ule&query=XML::Writer
The XML::Handler::YAWriter module
http://search.cpan.org/search?mode=mod
ule&query=XML::Handler::YAWriter
The HTML::Generator module
http://search.cpan.org/search?mode=mod
ule&query=HTML::Generator
Copyright © 2010-2025 Platon Technologies, s.r.o.           Home | Man pages | tLDP | Documents | Utilities | About
Design by styleshout