# perldoc > XML::Parser::Expat

---
type: CommandReference
command: XML::Parser::Expat
mode: perldoc
section: ""
source: perldoc
---

## Quick Reference

- `$parser = XML::Parser::Expat->new(...)` — create new parser with options
- `$parser->setHandlers('Start' => \&sh, 'End' => \&eh, 'Char' => \&ch)` — register event handlers
- `$parser->parse($source)` — parse XML from string or open filehandle
- `$parser->parsefile('file.xml')` — parse XML file by name
- `$parser->namespace($name)` — get namespace URI for a name
- `$parser->eq_name($name1, $name2)` — compare names with namespace awareness
- `$parser->current_line` — get current line number in parse
- `$parser->release` — break circular references to free memory

## Name

Lowlevel access to James Clark's expat XML parser

## Synopsis

perl
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) if ($el eq 'special');
}
## Description

This module provides an interface to James Clark's XML parser, expat. A single instance can only parse one document. Expat is event‑based: as the parser recognizes parts of the document (e.g., start/end of an element), registered handlers are called with suitable parameters.

## Options

Constructor options passed to `XML::Parser::Expat->new`:

- `ProtocolEncoding` — encoding name (default none). Built‑in: UTF-8, ISO-8859-1, UTF-16, US-ASCII. Overrides XML declaration.
- `Namespaces` — boolean, enable namespace processing (default off). Consumes `xmlns` attributes and strips prefixes.
- `NoExpand` — boolean, if true and a default handler is set, the default handler is called for entity references in text (not in attribute values).
- `Stream_Delimiter` — string; when found alone on a line parsing from a stream, ends parse (intended for MIME multipart).
- `ErrorContext` — integer, number of context lines to show on error.
- `ParseParamEnt` — boolean, allows reading external DTD and expanding parameter entities (unless standalone="yes").
- `Base` — base URI for resolving relative paths (also set via `base` method).

## Methods

### Construction and Parsing

- `new` — constructor (see Options above)
- `parse(SOURCE)` — parse XML document. SOURCE can be a string or an open IO::Handle. Croaks if called more than once per instance.
- `parsestring` — deprecated; use `parse`
- `parsefile` — parse XML document from a file by name (dies if called twice)
- `finish` — unset all handlers (including internal context handlers) and continue parsing to end; faster than normal parsing
- `release` — break circular references; makes instance unusable. Must be called when using `XML::Parser::Expat` directly.

### Event Handlers

- `setHandlers(event => \&handler, ...)` — register handlers. Returns list of previous type‑handler pairs. If a handler is set to false, it is unset. Recognized events (with parameters):
  - `Start` (Parser, Element, Attr, Val, ...)
  - `End` (Parser, Element)
  - `Char` (Parser, String) — in UTF‑8
  - `Proc` (Parser, Target, Data)
  - `Comment` (Parser, String)
  - `CdataStart` (Parser)
  - `CdataEnd` (Parser)
  - `Default` (Parser, String) — for characters without a registered handler (UTF‑8)
  - `Unparsed` (Parser, Entity, Base, Sysid, Pubid, Notation)
  - `Notation` (Parser, Notation, Base, Sysid, Pubid)
  - `ExternEnt` (Parser, Base, Sysid, Pubid) — must return string, open filehandle, or undef (error)
  - `ExternEntFin` (Parser) — cleanup after external entity parsed
  - `Entity` (Parser, Name, Val, Sysid, Pubid, Ndata, IsParam) — for internal/external entity declarations
  - `Element` (Parser, Name, Model) — content model as `XML::Parser::ContentModel` object
  - `Attlist` (Parser, Elname, Attname, Type, Default, Fixed)
  - `Doctype` (Parser, Name, Sysid, Pubid, Internal)
  - `DoctypeFin` (Parser) — after DOCTYPE declaration parsed
  - `XMLDecl` (Parser, Version, Encoding, Standalone)
- `default_current` — (deprecated) send current event sequence to default handler

### Namespace Methods

- `namespace(NAME)` — return namespace URI for the name, or undef if none
- `eq_name(NAME1, NAME2)` — return true if names are identical (same name and namespace)
- `generate_ns_name(NAMESPACE)` — return a name associated with the given namespace URI (not prefix)
- `new_ns_prefixes` — (call from start handler) returns list of namespace prefixes declared on this start tag; '#default' for default namespace
- `expand_ns_prefix(PREFIX)` — return URI bound to prefix; undef if not bound; use '#default' for default namespace
- `current_ns_prefixes` — return list of currently bound namespace prefixes (includes '#default' if bound)

### Context and Position

- `context` — list of element names for open elements, innermost last
- `current_element` — name of innermost open element (parent of current tag inside start/end handlers)
- `in_element(NAME)` — true if NAME equals innermost open element (use `generate_ns_name` for namespace‑aware check)
- `within_element(NAME)` — returns count of NAME in context list
- `depth` — size of context list
- `element_index` — depth‑first visit order (0 outside root, 1 for root start)
- `skip_until(INDEX)` — suspend all handlers until start tag with element index == INDEX is seen
- `current_line` — returns current line number in parse
- `current_column` — returns current column number
- `current_byte` — returns current byte position
- `position_in_context(LINES)` — returns string showing parse position with LINES context lines on either side

### String Retrieval

- `recognized_string` — UTF‑8 string that triggered the current handler (not meaningful inside declaration handlers)
- `original_string` — verbatim string from document in original encoding (not meaningful inside declaration handlers)
- `xml_escape(TEXT, ...)` — returns TEXT with markup characters (`<>&"'`) turned into character entities; additional characters can be passed to also escape them

### Error Handling

- `xpcroak(MESSAGE)` — croak with MESSAGE plus current line number and ErrorContext
- `xpcarp(MESSAGE)` — carp with MESSAGE plus current line number and ErrorContext

### Attribute Handling

- `specified_attr` — returns number of explicitly specified attributes in the start handler list; defaulted attributes come after this index
- `is_defaulted` — no longer works; use `specified_attr`

### Base URI

- `base(NEWBASE)` — get/set the base URI for resolving relative URIs

## Functions

- `XML::Parser::Expat::load_encoding(ENCODING)` — load an external encoding. ENCODING is a name or file path. Basename is lowercased and `.enc` is appended. Looks in `@Encoding_Path`. Stored in `%Encoding_Table`. Called automatically by expat for unknown encodings.

## XML::Parser::ContentModel Methods

Methods on objects passed to the `Element` handler:

- `isempty` — true if model is EMPTY
- `isany` — true if model is ANY
- `ismixed` — true if model is `(#PCDATA)` or `(#PCDATA|...)*`
- `isname` — true if object is an element name
- `ischoice` — true if object is a choice of content particles
- `isseq` — true if object is a sequence of content particles
- `quant` — returns undef or quantifier string (`?`, `*`, `+`)
- `children` — returns undef (for pure PCDATA) or array of component content particles

## XML::Parser::ExpatNB

The subclass `XML::Parser::ExpatNB` provides non‑blocking access. It does not support `parse`, `parsestring`, or `parsefile`, but adds:

- `parse_more(TEXT)` — feed more text to the parser
- `parse_done` — signal that the whole document has been provided

## See Also

- `XML::Parser` — higher‑level interface
- `XML::Parser::ContentModel` — content model details
- `XML::Parser::ExpatNB` — non‑blocking variant
- expat library documentation