Expat(3)
Expat(3) Β· User Contributed Perl Documentation Β· okay so this is the manual for XML::Parser::Expat, and she is lowkey a big deal π
β¨
πΈ NAME πΈ
XML::Parser::Expat β lowlevel access to James Clark's expat XML parser. It's giving backstage-pass energy to the parser itself, and honestly? Iconic.
π¦ SYNOPSIS π¦
Here's the whole vibe in code form, bestie β literally copy it exactly:
use XML::Parser::Expat;
$parser = XML::Parser::Expat->new;
$parser->setHandlers('Start' => \&sh,
'End' => \&eh,
'Char' => \&ch);
open(my $fh, '<', 'info.xml') or die "Couldn't open";
$parser->parse($fh);
close($fh);
# $parser->parse('<foo id="me"> here <em>we</em> go </foo>');
sub sh
{
my ($p, $el, %atts) = @_;
$p->setHandlers('Char' => \&spec)
if ($el eq 'special');
...
}
sub eh
{
my ($p, $el) = @_;
$p->setHandlers('Char' => \&ch) # Special elements won't contain
if ($el eq 'special'); # other special elements
...
}
β¨ DESCRIPTION β¨
okay so this module is your interface to James Clark's XML parser, expat. And like expat itself, one parser instance can only parse one document β no reuse, no second chances, bestie. Calls to parsestring after the first for a given instance will die. Periodt. π
π¨ bestie warning: one instance = one document. Callingparsestringagain on the same instance willdie.
Expat (and XML::Parser::Expat) are event based. As the parser recognizes parts of the document β say the start or end of an XML element β then any handlers registered for that type of an event are called with suitable parameters. It's literally main character energy for callbacks. π
π METHODS π
π new π
This is a class method, the constructor for XML::Parser::Expat. Options are passed as keyword value pairs. The recognized options are:
ProtocolEncodingβ The protocol encoding name. The default is none. The expat built-in encodings are:UTF-8,ISO-8859-1,UTF-16, andUS-ASCII. Other encodings may be used if they have encoding maps in one of the directories in the@Encoding_Pathlist. Setting the protocol encoding overrides any encoding in the XML declaration. β¨Namespacesβ When this option is given with a true value, then the parser does namespace processing. By default, namespace processing is turned off. When it is turned on, the parser consumesxmlnsattributes and strips off prefixes from element and attributes names where those prefixes have a defined namespace. A name's namespace can be found using thenamespacemethod and two names can be checked for absolute equality with theeq_namemethod. Slay. π¦NoExpandβ Normally, the parser will try to expand references to entities defined in the internal subset. If this option is set to a true value, and a default handler is also set, then the default handler will be called when an entity reference is seen in text. This has no effect if a default handler has not been registered, and it has no effect on the expansion of entity references inside attribute values. No cap. πStream_Delimiterβ This option takes a string value. When this string is found alone on a line while parsing from a stream, then the parse is ended as if it saw an end of file. The intended use is with a stream of xml documents in a MIME multipart format. The string should not contain a trailing newline. πErrorContextβ When this option is defined, errors are reported in context. The value ofErrorContextshould be the number of lines to show on either side of the line in which the error occurred. Very "let me show you exactly where it went wrong" of her. πParseParamEntβ Unless standalone is set to"yes"in the XML declaration, setting this to a true value allows the external DTD to be read, and parameter entities to be parsed and expanded. π«ΆBaseβ The base to use for relative pathnames or URLs. This can also be done by using thebasemethod. π
π«Ά setHandlers(TYPE, HANDLER [, TYPE, HANDLER [...]]) π«Ά
This method registers handlers for the various events. If no handlers are registered, then a call to parsestring or parsefile will only determine if the corresponding XML document is well formed (by returning without error.) This may be called from within a handler, after the parse has started. Obsessed with the flexibility, honestly.
Setting a handler to something that evaluates to false unsets that handler. β¨
This method returns a list of type, handler pairs corresponding to the input. The handlers returned are the ones that were in effect before the call to setHandlers. iykyk.
The recognized events and the parameters passed to the corresponding handlers are:
Startβ(Parser, Element [, Attr, Val [,...]]). This event is generated when an XML start tag is recognized.Parseris anXML::Parser::Expatinstance.Elementis the name of the XML element that is opened with the start tag. TheAttr&Valpairs are generated for each attribute in the start tag. π₯Endβ(Parser, Element). This event is generated when an XML end tag is recognized. Note that an XML empty tag (<foo/>) generates both a start and an end event. There is always a lower level start and end handler installed that wrap the corresponding callbacks. This is to handle the context mechanism. A consequence of this is that the default handler (see below) will not see a start tag or end tag unless thedefault_currentmethod is called. πCharβ(Parser, String). This event is generated when non-markup is recognized. The non-markup sequence of characters is inString. A single non-markup sequence of characters may generate multiple calls to this handler. Whatever the encoding of the string in the original document, this is given to the handler inUTF-8. πΈProcβ(Parser, Target, Data). This event is generated when a processing instruction is recognized. πCommentβ(Parser, String). This event is generated when a comment is recognized. π¬CdataStartβ(Parser). This is called at the start of a CDATA section. βCdataEndβ(Parser). This is called at the end of a CDATA section. βDefaultβ(Parser, String). This is called for any characters that don't have a registered handler. This includes both characters that are part of markup for which no events are generated (markup declarations) and characters that could generate events, but for which no handler has been registered. Whatever the encoding in the original document, the string is returned to the handler inUTF-8. πUnparsedβ(Parser, Entity, Base, Sysid, Pubid, Notation). This is called for a declaration of an unparsed entity.Entityis the name of the entity.Baseis the base to be used for resolving a relative URI.Sysidis the system id.Pubidis the public id.Notationis the notation name.BaseandPubidmay be undefined. π¦Notationβ(Parser, Notation, Base, Sysid, Pubid). This is called for a declaration of notation.Notationis the notation name.Baseis the base to be used for resolving a relative URI.Sysidis the system id.Pubidis the public id.Base,Sysid, andPubidmay all be undefined. πExternEntβ(Parser, Base, Sysid, Pubid). This is called when an external entity is referenced.Baseis the base to be used for resolving a relative URI.Sysidis the system id.Pubidis the public id.BaseandPubidmay be undefined. This handler should either return a string, which represents the contents of the external entity, or return an open filehandle that can be read to obtain the contents of the external entity, or returnundef, which indicates the external entity couldn't be found and will generate a parse error. If an open filehandle is returned, it must be returned as either a glob (*FOO) or as a reference to a glob (e.g. an instance ofIO::Handle). π«ΆExternEntFinβ(Parser). This is called after an external entity has been parsed. It allows applications to perform cleanup on actions performed in the aboveExternEnthandler. π§Entityβ(Parser, Name, Val, Sysid, Pubid, Ndata, IsParam). This is called when an entity is declared. For internal entities, theValparameter will contain the value and the remaining three parameters will be undefined. For external entities, theValparameter will be undefined, theSysidparameter will have the system id, thePubidparameter will have the public id if it was provided (it will be undefined otherwise), theNdataparameter will contain the notation for unparsed entities. If this is a parameter entity declaration, then theIsParamparameter is true. Note that this handler and theUnparsedhandler above overlap. If both are set, then this handler will not be called for unparsed entities. πElementβ(Parser, Name, Model). The element handler is called when an element declaration is found.Nameis the element name, andModelis the content model as anXML::Parser::ContentModelobject. See"XML::Parser::ContentModel Methods"for methods available for this class. πAttlistβ(Parser, Elname, Attname, Type, Default, Fixed). This handler is called for each attribute in anATTLISTdeclaration. So anATTLISTdeclaration that has multiple attributes will generate multiple calls to this handler. TheElnameparameter is the name of the element with which the attribute is being associated. TheAttnameparameter is the name of the attribute.Typeis the attribute type, given as a string.Defaultis the default value, which will either be"#REQUIRED","#IMPLIED"or a quoted string (i.e. the returned string will begin and end with a quote character). IfFixedis true, then this is a fixed attribute. πDoctypeβ(Parser, Name, Sysid, Pubid, Internal)- ok so there's also a handler for DOCTYPE declarations π
β
Nameis the document type name.Sysidis the system id of the document type, if it was provided, otherwise it's undefined.Pubidis the public id of the document type, which will be undefined if no public id was given.Internalwill be true or false, telling you whether or not the doctype declaration contains an internal subset. - DoctypeFin (Parser) β this one fires after parsing of the DOCTYPE declaration has finished, including any internal or external DTD declarations. like, the whole thing is done-done β¨
- XMLDecl (Parser, Version, Encoding, Standalone) β called for XML declarations, obviously π.
Versionis a string containing the version.Encodingis either undefined or contains an encoding string.Standaloneis either undefined, or true or false. Undefined means no standalone parameter was given in the XML declaration at all. True or false indicates "yes" or "no" respectively. slay.
π¦ namespace(name)
Returns the URI of the namespace that the name belongs to. If the name doesn't belong to any namespace, an undef comes back. β οΈ Heads up: this is only valid on names received through the Start or End handlers from a single document, or through a call to the generate_ns_name method. In other words β do not use names generated from one instance of XML::Parser::Expat with other instances. no cap, that's a whole mess waiting to happen π
π eq_name(name1, name2)
Returns true if name1 and name2 are identical (i.e. same name and from the same namespace). This is only meaningful if both names were obtained through the Start or End handlers from a single document, or through a call to the generate_ns_name method. iykyk π
πΈ generate_ns_name(name, namespace)
Returns a name, associated with a given namespace, that's good for using with the above 2 methods. The namespace argument should be the namespace URI, not a prefix. lowkey important, bestie π
π new_ns_prefixes
When called from a start tag handler, returns namespace prefixes declared with this start tag. If you call it anywhere else (or if there were no namespace prefixes declared), it returns an empty list. Setting of the default namespace is indicated with '#default' as a prefix. cute.
β expand_ns_prefix(prefix)
Returns the uri to which the given prefix is currently bound. Returns undef if the prefix isn't currently bound. Use '#default' to find the current binding of the default namespace (if any). π«Ά
π current_ns_prefixes
Returns a list of currently bound namespace prefixes. The order of the the prefixes in the list has no meaning (yes, "the the", the original said it, we're keeping it, iconic π). If the default namespace is currently bound, '#default' appears in the list.
π recognized_string
Returns the string from the document that was recognized in order to call the current handler. For instance, when called from a start handler, it will give us the start-tag string. The string is encoded in UTF-8. π§ Ngl, this method doesn't return a meaningful string inside declaration handlers.
π¦ original_string
Returns the verbatim string from the document that was recognized in order to call the current handler. The string is in the original document encoding. Same deal as above: this method doesn't return a meaningful string inside declaration handlers.
π default_current
When called from a handler, causes the sequence of characters that generated the corresponding event to be sent to the default handler (if one is registered). β οΈ Use of this method is deprecated in favor the recognized_string method, which you can use without installing a default handler. Also: this method doesn't deliver a meaningful string to the default handler when called from inside declaration handlers. so... yeah, it's giving legacy π
π₯ xpcroak(message)
Concatenate onto the given message the current line number within the XML document plus the message implied by ErrorContext. Then croak with the formed message. it will ruin someone's day, and that someone might be you π
πΈ xpcarp(message)
Concatenate onto the given message the current line number within the XML document plus the message implied by ErrorContext. Then carp with the formed message. gentler vibes, same info π
β¨ current_line
Returns the line number of the current position of the parse.
β¨ current_column
Returns the column number of the current position of the parse.
β¨ current_byte
Returns the current position of the parse.
π«Ά base([NEWBASE]);
Returns the current value of the base for resolving relative URIs. If NEWBASE is supplied, changes the base to that value. (yes the semicolon is part of the heading, we don't make the rules π)
π context
Returns a list of element names that represent open elements, with the last one being the innermost. Inside start and end tag handlers, this will be the tag of the parent element. main character energy honestly.
π current_element
Returns the name of the innermost currently opened element. Inside start or end handlers, returns the parent of the element associated with those tags.
π in_element(NAME)
Returns true if NAME is equal to the name of the innermost currently opened element. If namespace processing is being used and you want to check against a name that may be in a namespace, then use the generate_ns_name method to create the NAME argument. don't skip that step bestie π
π within_element(NAME)
Returns the number of times the given name appears in the context list. If namespace processing is being used and you want to check against a name that may be in a namespace, then use the generate_ns_name method to create the NAME argument. same deal π
π¦ depth
Returns the size of the context list.
β element_index
Returns an integer that is the depth-first visit order of the current element. This will be zero outside of the root element. For example, this will return 1 when called from the start handler for the root element start tag. math but make it cute.
π§ skip_until(INDEX)
INDEX is an integer that represents an element index. When this method is called, all handlers are suspended until the start tag for an element that has an index number equal to INDEX is seen. If a start handler has been set, then this is the first tag that the start handler will see after skip_until has been called. literally fast-forwarding through the document π
πΈ position_in_context(LINES)
Returns a string that shows the current parse position. LINES should be an integer >= 0 that represents the number of lines on either side of the current parse line to place into the returned string. contextual queen π
π xml_escape(TEXT [, CHAR [, CHAR ...]])
Returns TEXT with markup characters turned into character entities. Any additional characters provided as arguments are also turned into character references where found in TEXT. very demure, very escaped π
π parse (SOURCE)
The SOURCE parameter should either be a string containing the whole XML document, or it should be an open IO::Handle. β οΈ Only a single document may be parsed for a given instance of XML::Parser::Expat, so this will croak if it's been called previously for this instance. one and done, babe.
π parsestring(XML_DOC_STRING)
Parses the given string as an XML document. Only a single document may be parsed for a given instance of XML::Parser::Expat, so this will die if either parsestring or parsefile has been called for this instance previously.
π«Ά This method is deprecated in favor of the parse method. still works, just, y'know. legacy.
π parsefile(FILENAME)
Parses the XML document in the given file. Will die if parsestring or parsefile has been called previously for this instance. same one-document-per-instance rule, no exceptions π€
π is_defaulted(ATTNAME)
NO LONGER WORKS. π¨ To find out if an attribute is defaulted please use the specified_attr method. rip to a real one, but she's gone.
β specified_attr
When the start handler receives lists of attributes and values, the non-defaulted (i.e. explicitly specified) attributes occur in the list first. This method returns the number of specified items in the list. So if this number is equal to the length of the list, there were no defaulted values. Otherwise the number points to the index of the first defaulted attribute name. the way that this is genuinely useful⦠obsessed.
π₯ finish
Unsets all handlers (including internal ones that set context), but expat continues parsing to the end of the document or until it finds an error. It should finish up a lot faster than with the handlers set. speedrun era πββοΈπ¨
π§ release
There are data structures used by XML::Parser::Expat that have circular references. This means that these structures will never be garbage collected unless these references are explicitly broken. Calling this method breaks those references (and makes the instance unusable). π
β οΈ Normally, higher level calls handle this for you, but if you are using XML::Parser::Expat directly, then it's your responsibility to call it. don't forget, bestie, or your memory will simply never come back π
π XML::Parser::ContentModel Methods
The element declaration handlers are passed objects of this class as the content model of the element declaration. They also represent content particles, components of a content model. so they're doing double duty, iconic β¨
When referred to as a string, these objects are automagically converted to a string representation of the model (or content particle). "automagically" β the manpage said it, not me π
π isempty
This method returns true if the object is "EMPTY", false otherwise.
π isany
This method returns true if the object is "ANY", false otherwise.
π ismixed
This method returns true if the object is "(#PCDATA)" or "(#PCDATA|...)*", false otherwise.
π isname
This method returns whether or not the object is an element name.
π ischoice
This method returns true if the object is a choice of content particles.
π isseq
This method returns true if the object is a sequence of content particles.
β quant
This method returns undef or a string representing the quantifier ('?', '*', '+') associated with the model or particle.
π¦ children
This method returns undef or (for mixed, choice, and sequence types) an array of component content particles. There will always be at least one component for choices and sequences, but for a mixed content model of pure PCDATA, "(#PCDATA)", then an undef is returned. yes, really π«
π«Ά XML::Parser::ExpatNB Methods
The class XML::Parser::ExpatNB is a subclass of XML::Parser::Expat used for non-blocking access to the expat library. It does not support the parse, parsestring, or parsefile methods, but it does have these additional methods: π
π parse_more(DATA)
Feed expat more text to munch on. she's hungry, give her snacks π
π parse_done
Tell expat that it's gotten the whole document. that's a wrap, bestie π
β¨ FUNCTIONS β¨
okay so this is the function corner, bestie, and it's giving βone very specific utilityβ energy. π
XML::Parser::Expat::load_encoding(ENCODING)
This one loads an external encoding. ENCODING is either the name of an encoding or the name of a file β yes, either/or, she contains multitudes. β¨ The basename is converted to lowercase, and a .enc extension is appended unless thereβs one already there. Then, unless itβs an absolute pathname (i.e. begins with /), the first file by that name discovered in the @Encoding_Path path list is used.
The encoding in the file is loaded and kept in the %Encoding_Table table. Earlier encodings of the same name are replaced. π
This function is automatically called by expat when it encounters an encoding it doesnβt know about. Expat shouldnβt call this twice for the same encoding name. The only reason users should use this function is to explicitly load an encoding not contained in the @Encoding_Path list. no cap, thatβs the whole assignment. π«Ά
πΈ AUTHORS πΈ
- Larry Wall (
<larry@wall.org>) wrote version 1.0. π - Clark Cooper (
<coopercc@netheaven.com>) picked up support, changed the API for this version (2.x), provided documentation, and added some standard package features. β¨
π and thatβs the page, bestie! This is Expat(3) from perl v5.42.0, dated 2026-03-20 β iconic, documented, and officially wrapped. π
π¦ where this page comes from
- opensuse-leap 16.0: perl-XML-Parser 2.470.0-160000.3.1 Β· Artistic-2.0
- opensuse-leap 16.0: perl-XML-Parser 2.470.0-160000.3.1 Β· Artistic-2.0
- opensuse-leap 16.0: perl-XML-Parser 2.470.0-160000.3.1 Β· Artistic-2.0
- opensuse-leap 16.0: perl-XML-Parser 2.470.0-160000.3.1 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms