{
    "mode": "perldoc",
    "parameter": "XML::Parser",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/XML%3A%3AParser/json",
    "generated": "2026-06-10T16:26:00Z",
    "synopsis": "use XML::Parser;\n$p1 = XML::Parser->new(Style => 'Debug');\n$p1->parsefile('REC-xml-19980210.xml');\n$p1->parse('<foo id=\"me\">Hello World</foo>');\n# Alternative\n$p2 = XML::Parser->new(Handlers => {Start => \\&handlestart,\nEnd   => \\&handleend,\nChar  => \\&handlechar});\n$p2->parse($socket);\n# Another alternative\n$p3 = XML::Parser->new(ErrorContext => 2);\n$p3->setHandlers(Char    => \\&text,\nDefault => \\&other);\nopen(my $fh, 'xmlgenerator |');\n$p3->parse($foo, ProtocolEncoding => 'ISO-8859-1');\nclose($foo);\n$p3->parsefile('junk.xml', ErrorContext => 3);",
    "sections": {
        "NAME": {
            "content": "XML::Parser - A perl module for parsing XML documents\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use XML::Parser;\n\n$p1 = XML::Parser->new(Style => 'Debug');\n$p1->parsefile('REC-xml-19980210.xml');\n$p1->parse('<foo id=\"me\">Hello World</foo>');\n\n# Alternative\n$p2 = XML::Parser->new(Handlers => {Start => \\&handlestart,\nEnd   => \\&handleend,\nChar  => \\&handlechar});\n$p2->parse($socket);\n\n# Another alternative\n$p3 = XML::Parser->new(ErrorContext => 2);\n\n$p3->setHandlers(Char    => \\&text,\nDefault => \\&other);\n\nopen(my $fh, 'xmlgenerator |');\n$p3->parse($foo, ProtocolEncoding => 'ISO-8859-1');\nclose($foo);\n\n$p3->parsefile('junk.xml', ErrorContext => 3);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module provides ways to parse XML documents. It is built on top of XML::Parser::Expat,\nwhich is a lower level interface to James Clark's expat library. Each call to one of the parsing\nmethods creates a new instance of XML::Parser::Expat which is then used to parse the document.\nExpat options may be provided when the XML::Parser object is created. These options are then\npassed on to the Expat object on each parse call. They can also be given as extra arguments to\nthe parse methods, in which case they override options given at XML::Parser creation time.\n\nThe behavior of the parser is controlled either by \"STYLES\" and/or \"HANDLERS\" options, or by\n\"setHandlers\" method. These all provide mechanisms for XML::Parser to set the handlers needed by\nXML::Parser::Expat. If neither \"Style\" nor \"Handlers\" are specified, then parsing just checks\nthe document for being well-formed.\n\nWhen underlying handlers get called, they receive as their first parameter the *Expat* object,\nnot the Parser object.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "new This is a class method, the constructor for XML::Parser. Options are passed as keyword value\npairs. Recognized options are:\n\n*   Style\n\nThis option provides an easy way to create a given style of parser. The built in styles\nare: \"Debug\", \"Subs\", \"Tree\", \"Objects\", and \"Stream\". These are all defined in separate\npackages under \"XML::Parser::Style::*\", and you can find further documentation for each\nstyle both below, and in those packages.\n\nCustom styles can be provided by giving a full package name containing at least one\n'::'. This package should then have subs defined for each handler it wishes to have\ninstalled. See \"STYLES\" below for a discussion of each built in style.\n\n*   Handlers\n\nWhen provided, this option should be an anonymous hash containing as keys the type of\nhandler and as values a sub reference to handle that type of event. All the handlers get\npassed as their 1st parameter the instance of expat that is parsing the document.\nFurther details on handlers can be found in \"HANDLERS\". Any handler set here overrides\nthe corresponding handler set with the Style option.\n\n*   Pkg\n\nSome styles will refer to subs defined in this package. If not provided, it defaults to\nthe package which called the constructor.\n\n*   ErrorContext\n\nThis is an Expat option. When this option is defined, errors are reported in context.\nThe value should be the number of lines to show on either side of the line in which the\nerror occurred.\n\n*   ProtocolEncoding\n\nThis is an Expat option. This sets the protocol encoding name. It defaults to none. The\nbuilt-in encodings are: \"UTF-8\", \"ISO-8859-1\", \"UTF-16\", and \"US-ASCII\". Other encodings\nmay be used if they have encoding maps in one of the directories in the @EncodingPath\nlist. Check \"ENCODINGS\" for more information on encoding maps. Setting the protocol\nencoding overrides any encoding in the XML declaration.\n\n*   Namespaces\n\nThis is an Expat option. If this is set to a true value, then namespace processing is\ndone during the parse. See \"Namespaces\" in XML::Parser::Expat for further discussion of\nnamespace processing.\n\n*   NoExpand\n\nThis is an Expat option. Normally, the parser will try to expand references to entities\ndefined in the internal subset. If this option is set to a true value, and a default\nhandler is also set, then the default handler will be called when an entity reference is\nseen in text. This has no effect if a default handler has not been registered, and it\nhas no effect on the expansion of entity references inside attribute values.\n\n*   StreamDelimiter\n\nThis is an Expat option. It takes a string value. When this string is found alone on a\nline while parsing from a stream, then the parse is ended as if it saw an end of file.\nThe intended use is with a stream of xml documents in a MIME multipart format. The\nstring should not contain a trailing newline.\n\n*   ParseParamEnt\n\nThis is an Expat option. Unless standalone is set to \"yes\" in the XML declaration,\nsetting this to a true value allows the external DTD to be read, and parameter entities\nto be parsed and expanded.\n\n*   NoLWP\n\nThis option has no effect if the ExternEnt or ExternEntFin handlers are directly set.\nOtherwise, if true, it forces the use of a file based external entity handler.\n\n*   NonExpatOptions\n\nIf provided, this should be an anonymous hash whose keys are options that shouldn't be\npassed to Expat. This should only be of concern to those subclassing XML::Parser.\n",
            "subsections": [
                {
                    "name": "setHandlers",
                    "content": "This method registers handlers for various parser events. It overrides any previous handlers\nregistered through the Style or Handler options or through earlier calls to setHandlers. By\nproviding a false or undefined value as the handler, the existing handler can be unset.\n\nThis method returns a list of type, handler pairs corresponding to the input. The handlers\nreturned are the ones that were in effect prior to the call.\n\nSee a description of the handler types in \"HANDLERS\".\n"
                },
                {
                    "name": "parse",
                    "content": "The SOURCE parameter should either be a string containing the whole XML document, or it\nshould be an open IO::Handle. Constructor options to XML::Parser::Expat given as\nkeyword-value pairs may follow the SOURCE parameter. These override, for this call, any\noptions or attributes passed through from the XML::Parser instance.\n\nA die call is thrown if a parse error occurs. Otherwise it will return 1 or whatever is\nreturned from the Final handler, if one is installed. In other words, what parse may return\ndepends on the style.\n\nparsestring\nThis is just an alias for parse for backwards compatibility.\n"
                },
                {
                    "name": "parsefile",
                    "content": "Open FILE for reading, then call parse with the open handle. The file is closed no matter\nhow parse returns. Returns what parse returns.\n"
                },
                {
                    "name": "parse_start",
                    "content": "Create and return a new instance of XML::Parser::ExpatNB. Constructor options may be\nprovided. If an init handler has been provided, it is called before returning the ExpatNB\nobject. Documents are parsed by making incremental calls to the parsemore method of this\nobject, which takes a string. A single call to the parsedone method of this object, which\ntakes no arguments, indicates that the document is finished.\n\nIf there is a final handler installed, it is executed by the parsedone method before\nreturning and the parsedone method returns whatever is returned by the final handler.\n"
                }
            ]
        },
        "HANDLERS": {
            "content": "Expat is an event based parser. As the parser recognizes parts of the document (say the start or\nend tag for an XML element), then any handlers registered for that type of an event are called\nwith suitable parameters. All handlers receive an instance of XML::Parser::Expat as their first\nargument. See \"METHODS\" in XML::Parser::Expat for a discussion of the methods that can be called\non this object.\n\nInit                (Expat)\nThis is called just before the parsing of the document starts.\n\nFinal                (Expat)\nThis is called just after parsing has finished, but only if no errors occurred during the parse.\nParse returns what this returns.\n\nStart                (Expat, Element [, Attr, Val [,...]])\nThis event is generated when an XML start tag is recognized. Element is the name of the XML\nelement type that is opened with the start tag. The Attr & Val pairs are generated for each\nattribute in the start tag.\n\nEnd                (Expat, Element)\nThis event is generated when an XML end tag is recognized. Note that an XML empty tag (<foo/>)\ngenerates both a start and an end event.\n\nChar                (Expat, String)\nThis event is generated when non-markup is recognized. The non-markup sequence of characters is\nin String. A single non-markup sequence of characters may generate multiple calls to this\nhandler. Whatever the encoding of the string in the original document, this is given to the\nhandler in UTF-8.\n\nProc                (Expat, Target, Data)\nThis event is generated when a processing instruction is recognized.\n\nComment                (Expat, Data)\nThis event is generated when a comment is recognized.\n\nCdataStart        (Expat)\nThis is called at the start of a CDATA section.\n\nCdataEnd                (Expat)\nThis is called at the end of a CDATA section.\n\nDefault                (Expat, String)\nThis is called for any characters that don't have a registered handler. This includes both\ncharacters that are part of markup for which no events are generated (markup declarations) and\ncharacters that could generate events, but for which no handler has been registered.\n\nWhatever the encoding in the original document, the string is returned to the handler in UTF-8.\n\nUnparsed                (Expat, Entity, Base, Sysid, Pubid, Notation)\nThis is called for a declaration of an unparsed entity. Entity is the name of the entity. Base\nis the base to be used for resolving a relative URI. Sysid is the system id. Pubid is the public\nid. Notation is the notation name. Base and Pubid may be undefined.\n\nNotation                (Expat, Notation, Base, Sysid, Pubid)\nThis is called for a declaration of notation. Notation is the notation name. Base is the base to\nbe used for resolving a relative URI. Sysid is the system id. Pubid is the public id. Base,\nSysid, and Pubid may all be undefined.\n\nExternEnt        (Expat, Base, Sysid, Pubid)\nThis is called when an external entity is referenced. Base is the base to be used for resolving\na relative URI. Sysid is the system id. Pubid is the public id. Base, and Pubid may be\nundefined.\n\nThis handler should either return a string, which represents the contents of the external\nentity, or return an open filehandle that can be read to obtain the contents of the external\nentity, or return undef, which indicates the external entity couldn't be found and will generate\na parse error.\n\nIf an open filehandle is returned, it must be returned as either a glob (*FOO) or as a reference\nto a glob (e.g. an instance of IO::Handle).\n\nA default handler is installed for this event. The default handler is\nXML::Parser::lwpextenthandler unless the NoLWP option was provided with a true value,\notherwise XML::Parser::fileextenthandler is the default handler for external entities. Even\nwithout the NoLWP option, if the URI or LWP modules are missing, the file based handler ends up\nbeing used after giving a warning on the first external entity reference.\n\nThe LWP external entity handler will use proxies defined in the environment (httpproxy,\nftpproxy, etc.).\n\nPlease note that the LWP external entity handler reads the entire entity into a string and\nreturns it, where as the file handler opens a filehandle.\n\nAlso note that the file external entity handler will likely choke on absolute URIs or file names\nthat don't fit the conventions of the local operating system.\n\nThe expat base method can be used to set a basename for relative pathnames. If no basename is\ngiven, or if the basename is itself a relative name, then it is relative to the current working\ndirectory.\n\nExternEntFin        (Expat)\nThis is called after parsing an external entity. It's not called unless an ExternEnt handler is\nalso set. There is a default handler installed that pairs with the default ExternEnt handler.\n\nIf you're going to install your own ExternEnt handler, then you should set (or unset) this\nhandler too.\n\nEntity                (Expat, Name, Val, Sysid, Pubid, Ndata, IsParam)\nThis is called when an entity is declared. For internal entities, the Val parameter will contain\nthe value and the remaining three parameters will be undefined. For external entities, the Val\nparameter will be undefined, the Sysid parameter will have the system id, the Pubid parameter\nwill have the public id if it was provided (it will be undefined otherwise), the Ndata parameter\nwill contain the notation for unparsed entities. If this is a parameter entity declaration, then\nthe IsParam parameter is true.\n\nNote that this handler and the Unparsed handler above overlap. If both are set, then this\nhandler will not be called for unparsed entities.\n\nElement                (Expat, Name, Model)\nThe element handler is called when an element declaration is found. Name is the element name,\nand Model is the content model as an XML::Parser::Content object. See \"XML::Parser::ContentModel\nMethods\" in XML::Parser::Expat for methods available for this class.\n\nAttlist                (Expat, Elname, Attname, Type, Default, Fixed)\nThis handler is called for each attribute in an ATTLIST declaration. So an ATTLIST declaration\nthat has multiple attributes will generate multiple calls to this handler. The Elname parameter\nis the name of the element with which the attribute is being associated. The Attname parameter\nis the name of the attribute. Type is the attribute type, given as a string. Default is the\ndefault value, which will either be \"#REQUIRED\", \"#IMPLIED\" or a quoted string (i.e. the\nreturned string will begin and end with a quote character). If Fixed is true, then this is a\nfixed attribute.\n\nDoctype                (Expat, Name, Sysid, Pubid, Internal)\nThis handler is called for DOCTYPE declarations. Name is the document type name. Sysid is the\nsystem id of the document type, if it was provided, otherwise it's undefined. Pubid is the\npublic id of the document type, which will be undefined if no public id was given. Internal is\nthe internal subset, given as a string. If there was no internal subset, it will be undefined.\nInternal will contain all whitespace, comments, processing instructions, and declarations seen\nin the internal subset. The declarations will be there whether or not they have been processed\nby another handler (except for unparsed entities processed by the Unparsed handler). However,\ncomments and processing instructions will not appear if they've been processed by their\nrespective handlers.\n\n* DoctypeFin                (Parser)\nThis handler is called after parsing of the DOCTYPE declaration has finished, including any\ninternal or external DTD declarations.\n\nXMLDecl                (Expat, Version, Encoding, Standalone)\nThis handler is called for xml declarations. Version is a string containing the version.\nEncoding is either undefined or contains an encoding string. Standalone will be either true,\nfalse, or undefined if the standalone attribute is yes, no, or not made respectively.\n",
            "subsections": []
        },
        "STYLES": {
            "content": "",
            "subsections": [
                {
                    "name": "Debug",
                    "content": "This just prints out the document in outline form. Nothing special is returned by parse.\n"
                },
                {
                    "name": "Subs",
                    "content": "Each time an element starts, a sub by that name in the package specified by the Pkg option is\ncalled with the same parameters that the Start handler gets called with.\n\nEach time an element ends, a sub with that name appended with an underscore (\"\"), is called\nwith the same parameters that the End handler gets called with.\n\nNothing special is returned by parse.\n"
                },
                {
                    "name": "Tree",
                    "content": "Parse will return a parse tree for the document. Each node in the tree takes the form of a tag,\ncontent pair. Text nodes are represented with a pseudo-tag of \"0\" and the string that is their\ncontent. For elements, the content is an array reference. The first item in the array is a\n(possibly empty) hash reference containing attributes. The remainder of the array is a sequence\nof tag-content pairs representing the content of the element.\n\nSo for example the result of parsing:\n\n<foo><head id=\"a\">Hello <em>there</em></head><bar>Howdy<ref/></bar>do</foo>\n\nwould be:\n\nTag   Content\n==================================================================\n[foo, [{}, head, [{id => \"a\"}, 0, \"Hello \",  em, [{}, 0, \"there\"]],\nbar, [         {}, 0, \"Howdy\",  ref, [{}]],\n0, \"do\"\n]\n]\n\nThe root document \"foo\", has 3 children: a \"head\" element, a \"bar\" element and the text \"do\".\nAfter the empty attribute hash, these are represented in it's contents by 3 tag-content pairs.\n"
                },
                {
                    "name": "Objects",
                    "content": "This is similar to the Tree style, except that a hash object is created for each element. The\ncorresponding object will be in the class whose name is created by appending \"::\" and the\nelement name to the package set with the Pkg option. Non-markup text will be in the ::Characters\nclass. The contents of the corresponding object will be in an anonymous array that is the value\nof the Kids property for that object.\n"
                },
                {
                    "name": "Stream",
                    "content": "This style also uses the Pkg package. If none of the subs that this style looks for is there,\nthen the effect of parsing with this style is to print a canonical copy of the document without\ncomments or declarations. All the subs receive as their 1st parameter the Expat instance for the\ndocument they're parsing.\n\nIt looks for the following routines:\n\n*   StartDocument\n\nCalled at the start of the parse .\n\n*   StartTag\n\nCalled for every start tag with a second parameter of the element type. The $ variable will\ncontain a copy of the tag and the % variable will contain attribute values supplied for\nthat element.\n\n*   EndTag\n\nCalled for every end tag with a second parameter of the element type. The $ variable will\ncontain a copy of the end tag.\n\n*   Text\n\nCalled just before start or end tags with accumulated non-markup text in the $ variable.\n\n*   PI\n\nCalled for processing instructions. The $ variable will contain a copy of the PI and the\ntarget and data are sent as 2nd and 3rd parameters respectively.\n\n*   EndDocument\n\nCalled at conclusion of the parse.\n"
                }
            ]
        },
        "ENCODINGS": {
            "content": "XML documents may be encoded in character sets other than Unicode as long as they may be mapped\ninto the Unicode character set. Expat has further restrictions on encodings. Read the xmlparse.h\nheader file in the expat distribution to see details on these restrictions.\n\nExpat has built-in encodings for: \"UTF-8\", \"ISO-8859-1\", \"UTF-16\", and \"US-ASCII\". Encodings are\nset either through the XML declaration encoding attribute or through the ProtocolEncoding option\nto XML::Parser or XML::Parser::Expat.\n\nFor encodings other than the built-ins, expat calls the function loadencoding in the Expat\npackage with the encoding name. This function looks for a file in the path list\n@XML::Parser::Expat::EncodingPath, that matches the lower-cased name with a '.enc' extension.\nThe first one it finds, it loads.\n\nIf you wish to build your own encoding maps, check out the XML::Encoding module from CPAN.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Larry Wall <larry@wall.org> wrote version 1.0.\n\nClark Cooper <coopercc@netheaven.com> picked up support, changed the API for this version (2.x),\nprovided documentation, and added some standard package features.\n\nMatt Sergeant <matt@sergeant.org> is now maintaining XML::Parser\n",
            "subsections": []
        }
    },
    "summary": "XML::Parser - A perl module for parsing XML documents",
    "flags": [],
    "examples": [],
    "see_also": []
}