XML::Writer - Perl extension for writing XML documents. |
XML::Writer - Perl extension for writing XML documents.
use XML::Writer; use IO::File;
my $output = IO::File->new(">output.xml");
my $writer = XML::Writer->new(OUTPUT => $output); $writer->startTag("greeting", "class" => "simple"); $writer->characters("Hello, world!"); $writer->endTag("greeting"); $writer->end(); $output->close();
XML::Writer is a helper module for Perl programs that write an XML document. The module handles all escaping for attribute values and character data and constructs different types of markup, such as tags, comments, and processing instructions.
By default, the module performs several well-formedness checks to catch errors during output. This behaviour can be extremely useful during development and debugging, but it can be turned off for production-grade code.
The module can operate either in regular mode in or Namespace processing mode. In Namespace mode, the module will generate Namespace Declarations itself, and will perform additional checks on the output.
Additional support is available for a simplified data mode with no mixed content: newlines are automatically inserted around elements and elements can optionally be indented based as their nesting level.
new([$params])
my $writer = XML::Writer->new(OUTPUT => $output, NEWLINES => 1);
Arguments are an anonymous hash array of parameters:
print()
method;
if this parameter is not present, the module will write to standard output. If
a string reference is passed, it will capture the generated XML (as a string;
to get bytes use the Encode
module).
If the string self is passed, the output will be captured internally by the
object, and can be accessed via the to_string()
method, or by calling the
object in a string context.
my $writer = XML::Writer->new( OUTPUT => 'self' );
$writer->dataElement( hello => 'world' );
print $writer->to_string; # outputs <hello>world</hello> print "$writer"; # ditto
my $rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; my $writer = XML::Writer->new(NAMESPACES => 1); $writer->startTag([$rdfns, "Description"]);
The first member of the array is a namespace URI, and the second part is the local part of a qualified name. The module will automatically generate appropriate namespace declarations and will replace the URI part with a prefix.
my $rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; my $writer = XML::Writer->new(NAMESPACES => 1, PREFIX_MAP => {$rdfns => 'rdf'});
The keys in the hash table are namespace URIs, and the values are the associated prefixes. If there is not a preferred prefix for the namespace URI in this hash, then the module will automatically generate prefixes of the form ``__NS1'', ``__NS2'', etc.
To set the default namespace, use '' for the prefix.
end()
$writer->end();
If OUTPUT as been set to self, end()
will return the generated
document as well.
$writer->xmlDecl("UTF-8");
$writer->doctype("html");
comment($text)
$writer->comment("This is a comment");
$writer->pi('xml-stylesheet', 'href="style.css" type="text/css"');
If the processing instruction appears outside the document element (either before the first start tag or after the last end tag), the module will add a carriage return after it to improve readability.
The $target argument must be a single XML name. If you provide the $data argument, the module will insert its contents following the $target argument, separated by a single space.
$writer->startTag('doc', 'version' => '1.0', 'status' => 'draft', 'topic' => 'AT&T');
All start tags must eventually have matching end tags.
startTag()
for details):
$writer->emptyTag('img', 'src' => 'portrait.jpg', 'alt' => 'Portrait of Emma.');
endTag([$name])
$writer->endTag('doc');
If the $name argument is omitted, then the module will automatically supply the name of the currently open element:
$writer->startTag('p'); $writer->endTag();
$writer->startTag($name [, $aname1 => $value1, ...]); $writer->characters($data); $writer->endTag($name);
characters($data)
$writer->characters("Here is the formula: "); $writer->characters("a < 100 && a > 5");
You may invoke this method only within the document element (i.e. after the first start tag and before the last end tag).
In data mode, you must not use this method to add whitespace between elements.
raw($data)
raw('<')
will print a literal < character. This
necessarily bypasses all well-formedness checking, and is therefore
only available in unsafe mode.
This can sometimes be useful for printing entities which are defined for your XML format but the module doesn't know about, for example for XHTML.
cdata($data)
characters()
but writes the data quoted in a CDATA section, that
is, between <![CDATA[ and ]]>. If the data to be written itself
contains ]]>, it will be written as several consecutive CDATA
sections.
dataElement()
but the element content is written as one or more
CDATA sections (see cdata()
).
setOutput($output)
getOutput()
setDataMode($mode)
getDataMode()
setDataIndent($step)
getDataIndent()
in_element($name)
if ($writer->in_element('dl')) { $writer->startTag('dt'); } else { $writer->startTag('li'); }
within_element($name)
if ($writer->within_element('body')) { $writer->startTag('h1'); } else { $writer->startTag('title'); }
current_element()
my $name = $writer->current_element();
This is the equivalent of
my $name = $writer->ancestor(0);
ancestor($n)
As of 0.510, these methods may be used while writing a document.
To set the default namespace, omit the $prefix parameter or set it to ''.
removePrefix($uri)
forceNSDecl($uri)
With the default settings, the XML::Writer module can detect several basic XML well-formedness errors:
During Namespace processing, the module can detect the following additional errors:
To ensure full error detection, a program must also invoke the end method when it has finished writing a document:
$writer->startTag('greeting'); $writer->characters("Hello, world!"); $writer->endTag('greeting'); $writer->end();
This error reporting can catch many hidden bugs in Perl programs that create XML documents; however, if necessary, it can be turned off by providing an UNSAFE parameter:
my $writer = XML::Writer->new(OUTPUT => $output, UNSAFE => 1);
If OUTPUT has been set to self and the object has been called in a string context, it'll return the xml document.
end()
on the
document and prints it. Dies if OUTPUT has been set to anything else.
David Megginson <david@megginson.com>
Copyright (c) 1999 by Megginson Technologies.
Copyright (c) 2003 Ed Avis <ed@membled.com>
Copyright (c) 2004-2010 Joseph Walton <joe@kafsemo.org>
Redistribution and use in source and compiled forms, with or without modification, are permitted under any circumstances. No warranty.
XML::Parser
XML::Writer - Perl extension for writing XML documents. |