Skip to content

XMLIterator

do- edited this page Nov 5, 2022 · 17 revisions

Description

XMLIterator is a low level synchronous XML parser implemented as an ECMAScript iterator.

It takes a String containing a whole XML document and parses it giving out a sequence of XMLNode.

Nodes come isolated: parent and children fields are all null. It's up to API users to build hierarchies when necessary (or just to use XMLParser to get the complete document tree).

For self enclosed tags, a pair of objects (StartElement / EndElement) is emitted.

Usage

  const xml = fs.readFileSync ('small.xml', 'utf-8')
	
  for (const node of new XMLIterator (xml, {})) 
    if (node.isStartElement && node.localName === 'user') 
      return node.attributes.get ('id')  

Options

Name Default Description
entityResolver EntityResolver to be used with generated XMLNodes

Comparison to XMLLexer

XMLLexer and XMLIterator and are both low level XML parsers splitting pointy bracket delimited text to syntactically atomic tokens. But:

Name Proto XML Source Pro Contra
XMLLexer Transform Readable limited memory footprint with any XML size asynchronous by nature
XMLIterator Iterable String can be used in synchronous for ... of, e. g. in object constructors limited size XML only

So, XMLLexer vs. XMLIterator is basically like fs.createReadStream vs. fs.readFileSync.

Comparison to XMLParser

XMLParser and XMLIterator and are both synchronous XML parsers reading a complete String. But:

Name Proto Pro Contra
XMLIterator Iterable scans XML tag by tag, allows early completion doesn't build hierarchy
XMLParser none simple always allocates the complete document tree in memory

In fact, XMLParser is built on top of XMLIterator.

Clone this wiki locally