XML::Li...::Reader(3)
π
XML::LibXML::Reader(3) β User Contributed Perl Documentation π
okay bestie, welcome to the manual page for XML::LibXML::Reader. it's giving iconic Perl module energy, fr fr. π
β¨ NAME β¨
XML::LibXML::Reader β XML::LibXML::Reader β interface to libxml2 pull parser. like, that's the whole name, no cap. π¦
πΈ SYNOPSIS πΈ
bestie, here's the vibe. first way:
use XML::LibXML::Reader;
my $reader = XML::LibXML::Reader->new(location => "file.xml")
or die "cannot read file.xml\n";
while ($reader->read) {
processNode($reader);
}
sub processNode {
my $reader = shift;
printf "%d %d %s %d\n", ($reader->depth,
$reader->nodeType,
$reader->name,
$reader->isEmptyElement);
}
or, alternatively:
my $reader = XML::LibXML::Reader->new(location => "file.xml")
or die "cannot read file.xml\n";
$reader->preservePattern('//table/tr');
$reader->finish;
print $reader->document->toString(1);
π¦ DESCRIPTION π¦
okay so this is literally a perl interface to libxml2's pull-parser implementation xmlTextReader http://xmlsoft.org/html/libxml-xmlreader.html. this feature requires at least libxml2-2.6.21. pull-parsers (such as StAX in Java, or XmlReader in C#) use an iterator approach to parse XML documents. they are easier to program than event-based parser (SAX) and much more lightweight than tree-based parser (DOM), which load the complete tree into memory. so slay for memory efficiency. π
the Reader acts as a cursor going forward on the document stream and stopping at each node on the way. at every point, the DOM-like methods of the Reader object allow one to examine the current node (name, namespace, attributes, etc.) β it's giving main character energy, honestly. β¨
the user's code keeps control of the progress and simply calls the read() function repeatedly to progress to the next node in the document order. other functions provide means for skipping complete sub-trees, or nodes until a specific element, etc. so you're in charge, bestie. π
at every time, only a very limited portion of the document is kept in the memory, which makes the API more memory-efficient than using DOM. however, it is also possible to mix Reader with DOM. at every point the user may copy the current node (optionally expanded into a complete sub-tree) from the processed document to another DOM tree, or to instruct the Reader to collect sub-document in form of a DOM tree consisting of selected nodes. lowkey flexible. π
Reader API also supports namespaces, xml:base, entity handling, and DTD validation. Schema and RelaxNG validation support will probably be added in some later revision of the Perl interface. highkey looking forward to it. π
the naming of methods compared to libxml2 and C# XmlTextReader has been changed slightly to match the conventions of XML::LibXML. some functions have been changed or added with respect to the C interface. iykyk. π
π CONSTRUCTOR π
depending on the XML source, the Reader object can be created with either of:
my $reader = XML::LibXML::Reader->new( location => "file.xml", ... );
my $reader = XML::LibXML::Reader->new( string => $xml_string, ... );
my $reader = XML::LibXML::Reader->new( IO => $file_handle, ... );
my $reader = XML::LibXML::Reader->new( FD => fileno(STDIN), ... );
my $reader = XML::LibXML::Reader->new( DOM => $dom, ... );
where ... are (optional) reader options described below in "Reader options" or various parser options described in XML::LibXML::Parser. the constructor recognizes the following XML sources:
Source specification
locationβ read XML from a local file or (non-HTTPS) URL. bestie, URL but no HTTPS, periodt. π«Άstringβ read XML from a string. simple. β¨IOβ read XML a Perl IO filehandle. okay. πFDβ read XML from a file descriptor (bypasses Perl I/O layer, only applicable to filehandles for regular files or pipes). possibly faster thanIO. so if you're feeling speedy, go off. π₯DOMβ use reader API to walk through a pre-parsedXML::LibXML::Document. iconic. π
Reader options
encoding => $encodingβ override document encoding. you do you. πRelaxNG => $rng_schemaβ can be used to pass either aXML::LibXML::RelaxNGobject or a filename or (non-HTTPS) URL of a RelaxNG schema to the constructor. the schema is then used to validate the document as it is processed. no cap, validation on the fly. βSchema => $xsd_schemaβ can be used to pass either aXML::LibXML::Schemaobject or a filename or (non-HTTPS) URL of a W3C XSD schema to the constructor. the schema is then used to validate the document as it is processed. same vibe, XSD edition. π...β the reader further supports various parser options described inXML::LibXML::Parser(specifically those labeled by/reader/). go check those out. π¦
π₯ METHODS CONTROLLING PARSING PROGRESS π₯
read ()β moves the position to the next node in the stream, exposing its properties. returns1if the node was read successfully,0if there is no more nodes to read, or-1in case of error. so 1 is slay, 0 is done, -1 is not the vibe. πreadAttributeValue ()β parses an attribute value into one or more Text and EntityReference nodes. returns1in case of success,0if the reader was not positioned on an attribute node or all the attribute values have been read, or-1in case of error. okay bestie, stay on an attribute. πreadState ()β gets the read state of the reader. returns the state value, or-1in case of error. the module exports constants for the Reader states, seeSTATESbelow. so check that section. πdepth ()β the depth of the node in the tree, starts at0for the root node. root is 0, periodt. π±next ()β skip to the node following the current one in the document order while avoiding the sub-tree if any. returns1if the node was read successfully,0if there is no more nodes to read, or-1in case of error. it's giving skip and go next. πnextElement (localname?,nsURI?)β skip nodes following the current one in the document order until a specific element is reached. the element's name must be equal to a givenlocalnameif defined, and its namespace must equal to a givennsURIif defined. either of the arguments can be undefined (or omitted, in case of the latter or both). returns1if the element was found,0if there is no more nodes to read, or-1in case of error. so specific, we love that. π―nextPatternMatch (compiled_pattern)β skip nodes following the current one in the document order until an element matching a given compiled pattern is reached. seeXML::LibXML::Patternfor information on compiled patterns. see also the"matchesPattern"method. returns1if the element was found,0if there is no more nodes to read, or-1in case of error. pattern matching era. β¨skipSiblings ()β skip all nodes on the same or lower level until the first node on a higher level is reached. in particular, if the current node occurs in an element, the reader stops at the end tag of the parent element, otherwise it stops at a node immediately following the parent node. returns1if successful,0if end of the document is reached, or-1in case of error. bye siblings, we're going up. π¦nextSibling ()β it skips to the node following the current one in the document order while avoiding the sub-tree if any. returns1if the node was read successfully,0if there is no more nodes to read, or-1in case of error. sibling energy. π―nextSiblingElement (name?,nsURI?)β likenextElementbut only processes sibling elements of the current node (moving forward using"nextSibling ()"rather than"read ()", internally). returns1if the element was found,0if there is no more sibling nodes, or-1in case of error. so it's nextElement but for siblings only, no cap. πfinish ()β skip all remaining nodes in the document, reaching end of the document. returns1if successful,0in case of error. we're done here, periodt. πclose ()β this method releases any resources allocated by the current instance and closes any underlying input. it returns0on failure and1on success. this method is automatically called by the destructor when the reader is forgotten, therefore you do not have to call it directly. so like, it handles itself, main character energy. π
π METHODS EXTRACTING INFORMATION π
name ()β returns the qualified name of the current node, equal to(Prefix:)LocalName. iconic. β¨nodeType ()β returns the type of the current node. seeNODE TYPESbelow. go look. πlocalName ()β returns the local name of the node. simple. πprefix ()β returns the prefix of the namespace associated with the node. okay. πnamespaceURI ()β returns the URI defining the namespace associated with the node. URI slay. πisEmptyElement ()β check if the current node is empty, this is a bit bizarre in the sense that<a/>will be considered empty while<a></a>will not. so literally same thing but different, iykyk. πhasValue ()β returns true if the node can have a text value. does it have value? yes bestie. πvalue ()β provides the text value of the node if present orundefif not available. no value? undef. periodt. π¦readInnerXml ()β reads the contents of the current node, including child nodes and markup. returns a string containing the XML of the node's content, orundefif the current node is neither an element nor attribute, or has no child nodes. inner content, slay. β¨readOuterXml ()β reads the contents of the current node, including child nodes and markup. returns a string containing the XML of the node including its content, orundefif the current node is neither an element nor attribute. outer content, also slay. πnodePath()β returns a canonical location path to the current element from the root node to the current node. namespaced elements are matched by'*', because there is no way to declare prefixes within XPath patterns. unlikeXML::LibXML::Node::nodePath(), this function does not provide sibling counts (i.e. instead of e.g.'/a/b[1]'and'/a/b[2]'you get'/a/b'for both matches). so no sibling numbers, just vibes. πmatchesPattern(compiled_pattern)β returns a true value if the current node matches a compiled pattern. seeXML::LibXML::Patternfor information on compiled patterns. see also the"nextPatternMatch"method. pattern match, slay. π₯
π³ METHODS EXTRACTING DOM NODES π³
document()β bestie, this hands you the whole document tree the reader built. Use it to scoop up all the preserved nodes (peeppreserveNode()andpreservePatternfor how those get kept around).
β οΈ CAUTION: never ever use this function to modify the tree unless you've finished reading the entire document. Like, do not touch. Fr fr.
copyCurrentNode(deep)β this one's basically the DOMcopyNode()of the family. It gives you back a copy of the node currently being processed, as a matching DOM object. Passdeep = 1and you get the full sub-tree, no cap. πpreserveNode()β tells the XML Reader "hey, keep this current node in the document tree, it's important to me π ". Then once parsing is done, you can grab a document tree made of the preserved nodes and their content usingdocument().
Returns the node, or NULL if something went wrong. π
preservePattern(pattern,\%ns_map)β same idea but β¨pattern editionβ¨: this tells the XML Reader to preserve all nodes that match the pattern (which is a streaming XPath subset). Once parsing finishes,document()gives you a document tree of the preserved nodes and their content.
There's an optional second argument β a HASH reference mapping the prefixes used by the XPath to namespace URIs. Very organized of you, honestly.
The XPath subset you get here is described at
http://www.w3.org/TR/xmlschema-1/#Selector
and it matches the production
Path ::= ('.//')? ( Step '/' )* ( Step | '@' NameTest )
Returns a positive number on success, and -1 if it errored out. π
π METHODS PROCESSING ATTRIBUTES π
attributeCount()β how many attributes does the current node have? This tells you.hasAttributes()β does the node have attributes or not, that's the whole question. Yes/no vibes.getAttribute(name)β gives you the value of the attribute with that specified qualified name.
Returns a string with the value of the specified attribute, or undef if there's an error.
getAttributeNs(localName, namespaceURI)β gives you the value of the specified attribute.
Returns a string with the value of the specified attribute, or undef if there's an error.
getAttributeNo(no)β gives you the value of the attribute at the specified index, relative to the containing element.
Returns a string with the value of the specified attribute, or undef if there's an error.
isDefault()β returns true if the current attribute node was generated from the default value defined in the DTD. Spooky DTD-generated ghost attribute, love that for it. π»moveToAttribute(name)β moves the position to the attribute with the specified local name and namespace URI.
Returns 1 on success, -1 in case of error, 0 if not found.
moveToAttributeNo(no)β moves the position to the attribute at the specified index, relative to the containing element.
Returns 1 on success, -1 in case of error, 0 if not found.
moveToAttributeNs(localName,namespaceURI)β moves the position to the attribute with the specified local name and namespace URI.
Returns 1 on success, -1 in case of error, 0 if not found.
moveToFirstAttribute()β moves the position to the first attribute associated with the current node. First one up, let's go. π«Ά
Returns 1 on success, -1 in case of error, 0 if not found.
moveToNextAttribute()β moves the position to the next attribute associated with the current node.
Returns 1 on success, -1 in case of error, 0 if not found.
moveToElement()β moves the position to the node that contains the current attribute node. Like, back up to the parent element energy.
Returns 1 on success, -1 in case of error, 0 if not moved.
isNamespaceDecl()β figures out whether the current node is a namespace declaration rather than a regular attribute.
Returns 1 if the current node is a namespace declaration, 0 if it's a regular attribute or another type of node, or -1 in case of error.
π OTHER METHODS π
lookupNamespace(prefix)β resolves a namespace prefix in the scope of the current element.
Returns a string with the namespace URI that the prefix maps to, or undef in case of error.
encoding()β returns a string with the encoding of the document, orundefin case of error.standalone()β figures out the standalone status of the document being read. Returns1if the document was declared to be standalone,0if it was declared to be not standalone, or-1if the document didn't specify its standalone status, or in case of error.xmlVersion()β figures out the XML version of the document being read. Returns a string with the XML version of the document, orundefin case of error.baseURI()β returns the base URI of a given node.isValid()β retrieves the validity status from the parser.
Returns 1 if valid, 0 if no, and -1 in case of error.
xmlLang()β thexml:langscope within which the node resides.lineNumber()β gives you the line number of the current parsing point. πcolumnNumber()β gives you the column number of the current parsing point. πbyteConsumed()β this one gives you the current index of the parser relative to the start of the current entity. It's computed in bytes from the beginning, starting at zero and finishing at the size in bytes of the file (if you're parsing a file). The function is of constant cost if the input is UTF-8, but it can get pricey if you run it on non-UTF-8 input. πΈsetParserProp(prop => value, ...)β changes the parser processing behaviour by changing some of its internal properties. These properties are available with this function:load_ext_dtd,complete_attributes,validation,expand_entities.
Since some of these properties can only be changed before any read has been done, it's best to set the parsing properties at the constructor. Trust me on this one, bestie.
Returns 0 if the call was successful, or -1 in case of error.
getParserProp(prop)β get the value of a parser internal property. These property names can be used:load_ext_dtd,complete_attributes,validation,expand_entities.
Returns the value, usually 0 or 1, or -1 in case of error.
ποΈ DESTRUCTION ποΈ
XML::LibXML takes care of the reader object destruction when the last reference to the reader object goes out of scope. The document tree is preserved though, if either $reader->document or $reader->preserveNode was used and references to the document tree exist. So the tree lives on, iconic behaviour, honestly. π±
π§ NODE TYPES π§
The reader interface provides the following constants for node types (these constant symbols are exported by default, or if tag :types is used).
XML_READER_TYPE_NONE => 0
XML_READER_TYPE_ELEMENT => 1
XML_READER_TYPE_ATTRIBUTE => 2
XML_READER_TYPE_TEXT => 3
XML_READER_TYPE_CDATA => 4
XML_READER_TYPE_ENTITY_REFERENCE => 5
XML_READER_TYPE_ENTITY => 6
XML_READER_TYPE_PROCESSING_INSTRUCTION => 7
XML_READER_TYPE_COMMENT => 8
XML_READER_TYPE_DOCUMENT => 9
XML_READER_TYPE_DOCUMENT_TYPE => 10
XML_READER_TYPE_DOCUMENT_FRAGMENT => 11
XML_READER_TYPE_NOTATION => 12
XML_READER_TYPE_WHITESPACE => 13
XML_READER_TYPE_SIGNIFICANT_WHITESPACE => 14
XML_READER_TYPE_END_ELEMENT => 15
XML_READER_TYPE_END_ENTITY => 16
XML_READER_TYPE_XML_DECLARATION => 17
β STATES β
These constants represent the values returned by readState(). They're exported by default, or if tag :states is used:
XML_READER_NONE => -1
XML_READER_START => 0
XML_READER_ELEMENT => 1
XML_READER_END => 2
XML_READER_EMPTY => 3
XML_READER_BACKTRACK => 4
XML_READER_DONE => 5
XML_READER_ERROR => 6
π SEE ALSO π
- XML::LibXML::Pattern for information about compiled patterns.
http://xmlsoft.org/html/libxml-xmlreader.htmlhttp://dotgnu.org/pnetlib-doc/System/Xml/XmlTextReader.html
π«‘ ORIGINAL IMPLEMENTATION π«‘
Heiko Klein, <H.Klein@gmx.net<gt> and Petr Pajas
π AUTHORS π
Matt Sergeant, Christian Glahn, Petr Pajas
πΈ VERSION πΈ
2.0213
π COPYRIGHT π
2001-2007, AxKit.com Ltd.
2002-2006, Christian Glahn.
2006-2009, Petr Pajas.
π LICENSE π
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
okay that's the whole page bestie, we made it π this was perl v5.42.2, dated 2026-05-25, and it's the XML::Li...::Reader(3) page β go forth and parse slayfully π
β¨
π¦ where this page comes from
- fedora 43: perl-XML-LibXML 1:2.0213-1.fc43 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND MIT
- fedora 44: perl-XML-LibXML 1:2.0213-1.fc44 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms