# perldoc > XML::Generator

---
type: CommandReference
command: XML::Generator
mode: perldoc
section: 
source: perldoc
---

## Quick Reference

- `use XML::Generator ':pretty';` — import with pretty printing
- `print foo(bar({ baz => 3 }, bam()));` — generate XML via exported functions
- `my $X = XML::Generator->new(':pretty');` — object-oriented constructor
- `$gen->person($gen->name("Bob"), $gen->age(34), $gen->job("Accountant"));` — nested tags
- `$gen->$shoe_size("12 1/2")` — dynamic tag name using variable
- `$gen->person(\%attr)` — attributes via hash ref
- `$gen->open(['transaction'], 2000)` — namespace via array ref
- `$gen->xml($gen->RDF([...], ...))` — multiple namespaces with RDF example

## Name

Perl extension for generating XML

## Synopsis

perl
use XML::Generator ':pretty';

print foo(bar({ baz => 3 }, bam()),
          bar([ 'qux' => 'http://qux.com/' ], "Hey there, world"));
or

perl
my $X = XML::Generator->new(':pretty');

print $X->foo($X->bar({ baz => 3 }, $X->bam()),
              $X->bar([ 'qux' => 'http://qux.com/' ], "Hey there, world"));
Either yields:

xml
<foo xmlns:qux="http://qux.com/">
  <bar baz="3">
    <bam />
  </bar>
  <qux:bar>Hey there, world</qux:bar>
</foo>
## Options

Constructor arguments (can be combined with `:option` strings or `option => 'value'` pairs):

- `:std, :standard` — equivalent to `escape => 'always'`, `conformance => 'strict'`
- `:strict` — equivalent to `conformance => 'strict'`
- `:pretty[=N]` — equivalent to `escape => 'always'`, `conformance => 'strict'`, `pretty => N` (default 2)
- `namespace` — array ref with URI or (prefix, URI) pairs; sets global default namespace; prefixes added to tags if two or more elements
- `qualifiedAttributes, qualified_attributes` — set to true to prepend namespace prefix to attribute names (pre-0.99 behavior)
- `escape` — 'always' (escape &, <, >, "), 'unescaped' (allow backslash-escaped characters and scalar refs), 'high-bit' (escape high-bit bytes as numeric entities), 'apos' (escape single quotes), 'even-entities' (escape & even if part of entity). Comma-separated for combinations.
- `pretty` — integer for spaces per indent level, or string for custom indent (e.g., "\t")
- `conformance` — 'strict' enables XML syntax checks, special tags (xmlpi, xmlcmnt, xmldecl, xmldtd, xmlcdata, xml), and filters invalid characters
- `filterInvalidChars, filter_invalid_chars` — set to 1 to filter invalid XML 1.1 characters, 0 to disable
- `allowedXMLTags, allowed_xml_tags` — array ref of tag names that start with 'xml' to allow under strict conformance
- `empty` — 'self' (default, `<tag />`), 'compact' (`<tag/>`), 'close' (`<tag></tag>`), 'ignore' (non-compliant), 'args' (use count of arguments to decide)
- `version` — default XML version for declarations (default 1.0)
- `encoding` — default encoding for declarations
- `dtd` — array ref with [type, name, uri] for DTD; also accessible via `xmldtd` special tag

### Import Arguments

- `use XML::Generator ':import';` — exports `AUTOLOAD` to caller's package so undefined subroutines generate XML tags
- `use XML::Generator ':stacked';` — implies `:import` but cooperates with existing `AUTOLOAD` (see Stackable AUTOLOADs)
- Any other options imply `:import` and are passed to the generated `XML::Generator` object

### XML Conformance (when `conformance => 'strict'`)

- Entity and attribute names must start with alphabetic or underscore, then alphanumerics, underscores, periods, hyphens; not allowed to start with 'xml' (reserved)
- Special tags (only available under strict conformance):
  - `xmlpi` — processing instruction: first arg target, then attribute-value pairs
  - `xmlcmnt` — comment: arguments concatenated inside `<!-- ... -->`; `--` converted to `&#45;&#45;`
  - `xmldecl` — XML declaration: keyword-value pairs (version, encoding, standalone, dtd)
  - `xmldtd` — DTD: first arg is array ref of elements concatenated to form `<!DOCTYPE ...>`
  - `xmlcdata` — CDATA section: arguments concatenated inside `<![CDATA[...]]>`; `]]>` converted to `]]&gt;`
  - `xml` — final XML document: must be called with exactly one `XML::Generator`-produced XML document, plus optional comments/PIs; prepends XML declaration and re-blesses into non-embeddable class

## Examples

### Attributes with Tie::IxHash for order

perl
use Tie::IxHash;
tie my %attr, 'Tie::IxHash';
%attr = (name => 'Bob', age => 34, job => 'Accountant', 'shoe-size' => '12 1/2');
print $gen->person(\%attr);
Produces:

xml
<person name="Bob" age="34" job="Accountant" shoe-size="12 1/2" />
### Default namespace (single URI)

perl
my $html = XML::Generator->new(pretty => 2, namespace => ["http://www.w3.org/TR/REC-html40"]);
print $html->html($html->body($html->font({ face => 'Arial' }, "Hello, there")));
Yields:

xml
<html xmlns="http://www.w3.org/TR/REC-html40">
  <body>
    <font face="Arial">Hello, there</font>
  </body>
</html>
### Multiple namespaces (RDF example)

perl
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, { 'rdf:about' => "http://www.w3.org/People/EM/contact#me" },
      $gen->fullName($contactNS, 'Eric Miller'),
      $gen->mailbox($contactNS, { 'rdf:resource' => "mailto:em@w3.org" }),
      $gen->personalTitle($contactNS, 'Dr.'))));
Produces:

xml
<?xml version="1.0" standalone="yes"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#">
  <contact:Person rdf:about="http://www.w3.org/People/EM/contact#me">
    <contact:fullName>Eric Miller</contact:fullName>
    <contact:mailbox rdf:resource="mailto:em@w3.org" />
    <contact:personalTitle>Dr.</contact:personalTitle>
  </contact:Person>
</rdf:RDF>
## Stackable AUTOLOADs

As a simpler alternative to subclassing, the `AUTOLOAD` exported by `XML::Generator` can cooperate with an existing `AUTOLOAD` using the `:stacked` import option. Define your own `AUTOLOAD` before `use XML::Generator ':stacked';`. Return an empty list to let the default `XML::Generator` `AUTOLOAD` run, or any other value to abort and return that value.

Example:

perl
package MyGenerator;
my %entities = ( copy => '&copy;', nbsp => '&nbsp;' );
sub AUTOLOAD {
  my($tag) = our $AUTOLOAD =~ /.*::(.*)/;
  return $entities{$tag} if defined $entities{$tag};
  return;
}
use XML::Generator qw(:pretty :stacked);
Usage:

perl
use MyGenerator;
print html(head(title("My Title", copy())));
Produces:

xml
<html>
  <head>
    <title>My Title&copy;</title>
  </head>
</html>
## Creating a Subclass

To subclass `XML::Generator`, remember:

1. Useful utilities are in `XML::Generator::util`.
2. To construct a tag, call `SUPER::tagname`.
3. Fully-qualify utility methods.

Example subclass providing a custom HTML table:

perl
package XML::Generator::CustomHTML;
use base 'XML::Generator';

sub table {
    my $self = shift;
    my($namespace, $attr, @content) = $self->XML::Generator::util::parse_args(@_);
    if ( $self->XML::Generator::util::config('conformance') eq 'strict' ) {
        # ... special checks ...
    }
    # ... formatting magic ...
    return $self->SUPER::table($attr, $self->tr($self->td(@content)));
}
Alternative: use `XML::Generator::util::tag('table', $attr, ...)`.

## See Also

- [XML::Writer](https://www.chedong.com/phpMan.php/perldoc/XML%3A%3AWriter/markdown) module  
  <http://search.cpan.org/search?mode=module&query=XML::Writer>