{
    "mode": "perldoc",
    "parameter": "XML::Writer",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/XML%3A%3AWriter/json",
    "generated": "2026-06-12T06:20:53Z",
    "synopsis": "use XML::Writer;\nuse IO::File;\nmy $output = IO::File->new(\">output.xml\");\nmy $writer = XML::Writer->new(OUTPUT => $output);\n$writer->startTag(\"greeting\",\n\"class\" => \"simple\");\n$writer->characters(\"Hello, world!\");\n$writer->endTag(\"greeting\");\n$writer->end();\n$output->close();",
    "sections": {
        "NAME": {
            "content": "XML::Writer - Perl extension for writing XML documents.\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use XML::Writer;\nuse IO::File;\n\nmy $output = IO::File->new(\">output.xml\");\n\nmy $writer = XML::Writer->new(OUTPUT => $output);\n$writer->startTag(\"greeting\",\n\"class\" => \"simple\");\n$writer->characters(\"Hello, world!\");\n$writer->endTag(\"greeting\");\n$writer->end();\n$output->close();\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "XML::Writer is a helper module for Perl programs that write an XML document. The module handles\nall escaping for attribute values and character data and constructs different types of markup,\nsuch as tags, comments, and processing instructions.\n\nBy default, the module performs several well-formedness checks to catch errors during output.\nThis behaviour can be extremely useful during development and debugging, but it can be turned\noff for production-grade code.\n\nThe module can operate either in regular mode in or Namespace processing mode. In Namespace\nmode, the module will generate Namespace Declarations itself, and will perform additional checks\non the output.\n\nAdditional support is available for a simplified data mode with no mixed content: newlines are\nautomatically inserted around elements and elements can optionally be indented based as their\nnesting level.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "",
            "subsections": [
                {
                    "name": "Writing XML",
                    "content": ""
                },
                {
                    "name": "new",
                    "content": "Create a new XML::Writer object:\n\nmy $writer = XML::Writer->new(OUTPUT => $output, NEWLINES => 1);\n\nArguments are an anonymous hash array of parameters:\n\nOUTPUT\nAn object blessed into IO::Handle or one of its subclasses (such as IO::File), or a\nreference to a string, or any blessed object that has a print() method; if this\nparameter is not present, the module will write to standard output. If a string\nreference is passed, it will capture the generated XML (as a string; to get bytes use\nthe \"Encode\" module).\n\nIf the string *self* is passed, the output will be captured internally by the object,\nand can be accessed via the \"tostring()\" method, or by calling the object in a string\ncontext.\n\nmy $writer = XML::Writer->new( OUTPUT => 'self' );\n\n$writer->dataElement( hello => 'world' );\n\nprint $writer->tostring;  # outputs <hello>world</hello>\nprint \"$writer\";           # ditto\n\nNAMESPACES\nA true (1) or false (0, undef) value; if this parameter is present and its value is\ntrue, then the module will accept two-member array reference in the place of element and\nattribute names, as in the following example:\n\nmy $rdfns = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\";\nmy $writer = XML::Writer->new(NAMESPACES => 1);\n$writer->startTag([$rdfns, \"Description\"]);\n\nThe first member of the array is a namespace URI, and the second part is the local part\nof a qualified name. The module will automatically generate appropriate namespace\ndeclarations and will replace the URI part with a prefix.\n\nPREFIXMAP\nA hash reference; if this parameter is present and the module is performing namespace\nprocessing (see the NAMESPACES parameter), then the module will use this hash to look up\npreferred prefixes for namespace URIs:\n\nmy $rdfns = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\";\nmy $writer = XML::Writer->new(NAMESPACES => 1,\nPREFIXMAP => {$rdfns => 'rdf'});\n\nThe keys in the hash table are namespace URIs, and the values are the associated\nprefixes. If there is not a preferred prefix for the namespace URI in this hash, then\nthe module will automatically generate prefixes of the form \"NS1\", \"NS2\", etc.\n\nTo set the default namespace, use '' for the prefix.\n\nFORCEDNSDECLS\nAn array reference; if this parameter is present, the document element will contain\ndeclarations for all the given namespace URIs. Declaring namespaces in advance is\nparticularly useful when a large number of elements from a namespace are siblings, but\ndon't share a direct ancestor from the same namespace.\n\nNEWLINES\nA true or false value; if this parameter is present and its value is true, then the\nmodule will insert an extra newline before the closing delimiter of start, end, and\nempty tags to guarantee that the document does not end up as a single, long line. If the\nparameter is not present, the module will not insert the newlines.\n\nUNSAFE\nA true or false value; if this parameter is present and its value is true, then the\nmodule will skip most well-formedness error checking. If the parameter is not present,\nthe module will perform the well-formedness error checking by default. Turn off error\nchecking at your own risk!\n\nDATAMODE\nA true or false value; if this parameter is present and its value is true, then the\nmodule will enter a special data mode, inserting newlines automatically around elements\nand (unless UNSAFE is also specified) reporting an error if any element has both\ncharacters and elements as content.\n\nDATAINDENT\nA numeric value or white space; if this parameter is present, it represents the indent\nstep for elements in data mode (it will be ignored when not in data mode). If it is\nwhite space it will be repeated for each level of indentation.\n\nENCODING\nA character encoding to use for the output; currently this must be one of 'utf-8' or\n'us-ascii'. If present, it will be used for the underlying character encoding and as the\ndefault in the XML declaration. All character data should be passed as Unicode strings\nwhen an encoding is set.\n\nCHECKPRINT\nA true or false value; if this parameter is present and its value is true, all prints to\nthe underlying output will be checked for success. Failures will cause a croak rather\nthan being ignored.\n"
                },
                {
                    "name": "end",
                    "content": "Finish creating an XML document. This method will check that the document has exactly one\ndocument element, and that all start tags are closed:\n\n$writer->end();\n\nIf *OUTPUT* as been set to *self*, \"end()\" will return the generated document as well.\n"
                },
                {
                    "name": "xmlDecl",
                    "content": "Add an XML declaration to the beginning of an XML document. The version will always be\n\"1.0\". If you provide a non-null encoding or standalone argument, its value will appear in\nthe declaration (any non-null value for standalone except 'no' will automatically be\nconverted to 'yes'). If not given here, the encoding will be taken from the ENCODING\nargument. Pass the empty string to suppress this behaviour.\n\n$writer->xmlDecl(\"UTF-8\");\n"
                },
                {
                    "name": "doctype",
                    "content": "Add a DOCTYPE declaration to an XML document. The declaration must appear before the\nbeginning of the root element. If you provide a publicId, you must provide a systemId as\nwell, but you may provide just a system ID by passing 'undef' for the publicId.\n\n$writer->doctype(\"html\");\n"
                },
                {
                    "name": "comment",
                    "content": "Add a comment to an XML document. If the comment appears outside the document element\n(either before the first start tag or after the last end tag), the module will add a\ncarriage return after it to improve readability. In data mode, comments will be treated as\nempty tags:\n\n$writer->comment(\"This is a comment\");\n"
                },
                {
                    "name": "pi",
                    "content": "Add a processing instruction to an XML document:\n\n$writer->pi('xml-stylesheet', 'href=\"style.css\" type=\"text/css\"');\n\nIf the processing instruction appears outside the document element (either before the first\nstart tag or after the last end tag), the module will add a carriage return after it to\nimprove readability.\n\nThe $target argument must be a single XML name. If you provide the $data argument, the\nmodule will insert its contents following the $target argument, separated by a single space.\n"
                },
                {
                    "name": "startTag",
                    "content": "Add a start tag to an XML document. Any arguments after the element name are assumed to be\nname/value pairs for attributes: the module will escape all '&', '<', '>', and '\"'\ncharacters in the attribute values using the predefined XML entities:\n\n$writer->startTag('doc', 'version' => '1.0',\n'status' => 'draft',\n'topic' => 'AT&T');\n\nAll start tags must eventually have matching end tags.\n"
                },
                {
                    "name": "emptyTag",
                    "content": "Add an empty tag to an XML document. Any arguments after the element name are assumed to be\nname/value pairs for attributes (see startTag() for details):\n\n$writer->emptyTag('img', 'src' => 'portrait.jpg',\n'alt' => 'Portrait of Emma.');\n"
                },
                {
                    "name": "endTag",
                    "content": "Add an end tag to an XML document. The end tag must match the closest open start tag, and\nthere must be a matching and properly-nested end tag for every start tag:\n\n$writer->endTag('doc');\n\nIf the $name argument is omitted, then the module will automatically supply the name of the\ncurrently open element:\n\n$writer->startTag('p');\n$writer->endTag();\n"
                },
                {
                    "name": "dataElement",
                    "content": "Print an entire element containing only character data. This is equivalent to\n\n$writer->startTag($name [, $aname1 => $value1, ...]);\n$writer->characters($data);\n$writer->endTag($name);\n"
                },
                {
                    "name": "characters",
                    "content": "Add character data to an XML document. All '<', '>', and '&' characters in the $data\nargument will automatically be escaped using the predefined XML entities:\n\n$writer->characters(\"Here is the formula: \");\n$writer->characters(\"a < 100 && a > 5\");\n\nYou may invoke this method only within the document element (i.e. after the first start tag\nand before the last end tag).\n\nIn data mode, you must not use this method to add whitespace between elements.\n"
                },
                {
                    "name": "raw",
                    "content": "Print data completely unquoted and unchecked to the XML document. For example \"raw('<')\"\nwill print a literal < character. This necessarily bypasses all well-formedness checking,\nand is therefore only available in unsafe mode.\n\nThis can sometimes be useful for printing entities which are defined for your XML format but\nthe module doesn't know about, for example &nbsp; for XHTML.\n"
                },
                {
                    "name": "cdata",
                    "content": "As \"characters()\" but writes the data quoted in a CDATA section, that is, between <![CDATA[\nand ]]>. If the data to be written itself contains ]]>, it will be written as several\nconsecutive CDATA sections.\n"
                },
                {
                    "name": "cdataElement",
                    "content": "As \"dataElement()\" but the element content is written as one or more CDATA sections (see\n\"cdata()\").\n"
                },
                {
                    "name": "setOutput",
                    "content": "Set the current output destination, as in the OUTPUT parameter for the constructor.\n"
                },
                {
                    "name": "getOutput",
                    "content": "Return the current output destination, as in the OUTPUT parameter for the constructor.\n"
                },
                {
                    "name": "setDataMode",
                    "content": "Enable or disable data mode, as in the DATAMODE parameter for the constructor.\n"
                },
                {
                    "name": "getDataMode",
                    "content": "Return the current data mode, as in the DATAMODE parameter for the constructor.\n"
                },
                {
                    "name": "setDataIndent",
                    "content": "Set the indent step for data mode, as in the DATAINDENT parameter for the constructor.\n"
                },
                {
                    "name": "getDataIndent",
                    "content": "Return the indent step for data mode, as in the DATAINDENT parameter for the constructor.\n"
                },
                {
                    "name": "Querying XML",
                    "content": ""
                },
                {
                    "name": "in_element",
                    "content": "Return a true value if the most recent open element matches $name:\n\nif ($writer->inelement('dl')) {\n$writer->startTag('dt');\n} else {\n$writer->startTag('li');\n}\n"
                },
                {
                    "name": "within_element",
                    "content": "Return a true value if any open element matches $name:\n\nif ($writer->withinelement('body')) {\n$writer->startTag('h1');\n} else {\n$writer->startTag('title');\n}\n"
                },
                {
                    "name": "current_element",
                    "content": "Return the name of the currently open element:\n\nmy $name = $writer->currentelement();\n\nThis is the equivalent of\n\nmy $name = $writer->ancestor(0);\n"
                },
                {
                    "name": "ancestor",
                    "content": "Return the name of the nth ancestor, where $n=0 for the current open element.\n"
                },
                {
                    "name": "Additional Namespace Support",
                    "content": "As of 0.510, these methods may be used while writing a document.\n"
                },
                {
                    "name": "addPrefix",
                    "content": "Add a preferred mapping between a Namespace URI and a prefix. See also the PREFIXMAP\nconstructor parameter.\n\nTo set the default namespace, omit the $prefix parameter or set it to ''.\n"
                },
                {
                    "name": "removePrefix",
                    "content": "Remove a preferred mapping between a Namespace URI and a prefix.\n"
                },
                {
                    "name": "forceNSDecl",
                    "content": "Indicate that a namespace declaration for this URI should be included with the next element\nto be started.\n"
                }
            ]
        },
        "ERROR REPORTING": {
            "content": "With the default settings, the XML::Writer module can detect several basic XML well-formedness\nerrors:\n\n*   Lack of a (top-level) document element, or multiple document elements.\n\n*   Unclosed start tags.\n\n*   Misplaced delimiters in the contents of processing instructions or comments.\n\n*   Misplaced or duplicate XML declaration(s).\n\n*   Misplaced or duplicate DOCTYPE declaration(s).\n\n*   Mismatch between the document type name in the DOCTYPE declaration and the name of the\ndocument element.\n\n*   Mismatched start and end tags.\n\n*   Attempts to insert character data outside the document element.\n\n*   Duplicate attributes with the same name.\n\nDuring Namespace processing, the module can detect the following additional errors:\n\n*   Attempts to use PI targets or element or attribute names containing a colon.\n\n*   Attempts to use attributes with names beginning \"xmlns\".\n\nTo ensure full error detection, a program must also invoke the end method when it has finished\nwriting a document:\n\n$writer->startTag('greeting');\n$writer->characters(\"Hello, world!\");\n$writer->endTag('greeting');\n$writer->end();\n\nThis error reporting can catch many hidden bugs in Perl programs that create XML documents;\nhowever, if necessary, it can be turned off by providing an UNSAFE parameter:\n\nmy $writer = XML::Writer->new(OUTPUT => $output, UNSAFE => 1);\n\nPRINTING OUTPUT\nIf *OUTPUT* has been set to *self* and the object has been called in a string context, it'll\nreturn the xml document.\n\ntostring\nIf *OUTPUT* has been set to *self*, calls an implicit \"end()\" on the document and prints it.\nDies if *OUTPUT* has been set to anything else.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "David Megginson <david@megginson.com>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "Copyright (c) 1999 by Megginson Technologies.\n\nCopyright (c) 2003 Ed Avis <ed@membled.com>\n\nCopyright (c) 2004-2010 Joseph Walton <joe@kafsemo.org>\n\nRedistribution and use in source and compiled forms, with or without modification, are permitted\nunder any circumstances. No warranty.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "XML::Parser\n",
            "subsections": []
        }
    },
    "summary": "XML::Writer - Perl extension for writing XML documents.",
    "flags": [],
    "examples": [],
    "see_also": []
}