Skip to content

Coming from Java ​

For developers who know Java's XML APIs (JAXP, StAX, SAX and the DOM), this page maps each Java class, method and setting to its exemplar equivalent and lists the differences in behaviour.

The structure is the same: XMLInputFactory holds the configuration, creates the cursor and the event reader, and is passed to the SAX parser and the tree builders.

java
XMLInputFactory factory = XMLInputFactory.newFactory();
factory.setProperty(XMLInputFactory.IS_COALESCING, true);
XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(source));
while (reader.hasNext()) {
  if (reader.next() == XMLStreamConstants.START_ELEMENT) {
    System.out.println(reader.getLocalName() + " " + reader.getAttributeValue(null, "id"));
  }
}
ts
import { 
EventType
,
XMLInputFactory
} from '@exemplarjs/xml';
const
factory
= new
XMLInputFactory
({
coalescing
: true });
const
reader
=
factory
.
createStreamReader
(
source
);
while (
reader
.
hasNext
()) {
if (
reader
.
next
() ===
EventType
.
START_ELEMENT
) {
console
.
log
(
reader
.
localName
(),
reader
.
attribute
('id'));
} }

Classes ​

Reading ​

JavaexemplarGuide
XMLInputFactoryXMLInputFactory from @exemplarjs/xmlFactories and sources
XMLStreamReaderfactory.createStreamReader(source)Reading with the cursor
A non-blocking XMLStreamReader (Aalto)factory.createAsyncStreamReader(stream)Large files and streams
XMLStreamConstantsEventTypeReading with the cursor
StreamFilter, createFilteredReadercreateFilteredReader(reader, ...filters) from @exemplarjs/xml/filtersDropping content with filters
StreamReaderDelegateStreamReaderDelegate, createDelegatedReader from @exemplarjs/xml/filtersChanging content with delegates
XMLEventReaderfactory.createEventReader(source)Reading event objects
XMLEvent, StartElement, Characters, …XMLEvent, StartElementEvent, CharactersEvent, …Reading event objects
XMLEventFactoryXMLEventFactoryChanging events with a generator
EventFilter, createFilteredReadercreateFilteredReader(eventReader, ...filters) from @exemplarjs/xml/filtersReading event objects
EventReaderDelegateA generator function over the eventsChanging events with a generator
javax.xml.namespace.QNameQName from @exemplarjs/xmlNamespaces
InputSource, StreamSourceA source object such as { bytes, systemId, encoding }Factories and sources

SAX ​

JavaexemplarGuide
SAXParserFactory, SAXParser, XMLReadernew SAXParser(factory, options) from @exemplarjs/saxHandling events with SAX
ContentHandler, LexicalHandler, DTDHandler, DeclHandler, ErrorHandlerOne handler object implementing the callbacks requiredHandling events with SAX
DefaultHandler, DefaultHandler2A plain object; every method is optionalHandling events with SAX
Attributes, AttributesImplAttributes, AttributesImplHandling events with SAX
LocatorLocator, passed to setDocumentLocatorHandling events with SAX
XMLFilterImplXMLFilterImplSAX filters

Trees ​

JavaexemplarGuide
DocumentBuilderFactory, DocumentBuildernew DocumentBuilder(factory, options) from @exemplarjs/domBuilding and reading a DOM
org.w3c.dom.Document, Element, Node, …The same names from @exemplarjs/domBuilding and reading a DOM
DOMImplementationRegistryDOMImplementationRegistryBuilding and reading a DOM
LSSerializer, an identity Transformerwriter.writeNode(node), or XMLSerializerChanging and saving a DOM
DOMResultbuilder.createSAXHandler() at the end of a filter chainSAX filters

Writing ​

JavaexemplarGuide
XMLOutputFactoryXMLOutputFactory from @exemplarjs/writerWriting XML
XMLStreamWriteroutput.createStreamWriter(destination)Writing XML
XMLEventWriteroutput.createEventWriter(destination)Copying and changing documents
StringWriter, ByteArrayOutputStreamStringSink, BytesSinkWriting XML
OutputStreamA web WritableStream<Uint8Array>Writing XML
An identity Transformer from a reader to a resultwriter.copy(reader), writer.copyAsync(reader)Copying and changing documents
TransformerHandler writing SAX eventsoutput.createSAXHandler(destination)SAX filters

Resolvers, catalogs and validation ​

JavaexemplarGuide
EntityResolver, EntityResolver2, XMLResolverThe entityResolver optionResolvers and access
URIResolverThe uriResolver optionResolvers and access
CatalogManager.catalogResolver(features, files)catalogResolver({ files, prefer, defer, resolution }) from @exemplarjs/catalogCatalogs
ErrorHandler, XMLReporterThe errorHandler optionErrors and locations
SAXParseException, XMLStreamExceptionXMLErrorErrors and locations
IllegalArgumentExceptionInvalidArgumentError from @exemplarjs/xmlErrors and locations
IllegalStateExceptionIllegalStateError from @exemplarjs/xmlErrors and locations
setValidating(true)The validator option, with dtdValidator() from @exemplarjs/validationValidating against a DTD
setXIncludeAware(true)The xinclude option, with xincludeProcessor() from @exemplarjs/xincludeXInclude
XML Schema validation (javax.xml.validation)Not availableStandards and conformance

XPath and values ​

javax.xml.xpath is XPath 1.0 over the DOM. exemplar implements XPath 3.1 over the XDM tree, not the DOM, so the classes do not correspond one to one.

JavaexemplarGuide
XPathFactory, XPathnew XPathCompiler(options) from @exemplarjs/xpathGetting started with XPath
XPathExpressionXPathExecutable, from compiler.compile(expression)Getting started with XPath
evaluate(node, XPathConstants.NODESET)selectNodes(node)Getting results
XPathConstants.STRING, NUMBER, BOOLEANevaluateString, evaluateNumber, evaluateBooleanGetting results
NamespaceContextThe compiler's namespaces optionGetting started with XPath
XPathVariableResolverVariables declared in compile and bound at evaluationPassing variables
The DOM tree as the query targetnew XdmDocumentBuilder(factory).parse(source) from @exemplarjs/xdmThe XDM tree
javax.xml.datatype.XMLGregorianCalendarXMLGregorianCalendar from @exemplarjs/xdmDates, times and durations
javax.xml.datatype.DurationDuration from @exemplarjs/xdmDates, times and durations
BigDecimal, new BigDecimal(text)Decimal from @exemplarjs/xdm, Decimal.from(text)Getting results

Method names ​

Accessors drop Java's get prefix; other methods keep their names.

The cursor ​

StAX XMLStreamReaderexemplar
next(), hasNext(), nextTag(), close()The same
getEventType()eventType()
getLocalName(), getPrefix(), getNamespaceURI()localName(), prefix(), namespaceURI()
getName(), a QNamename(), the qualified name as a string, such as 'dc:title'
getText(), getElementText()text(), elementText()
isWhiteSpace()isWhitespace()
getAttributeValue(namespaceURI, localName)attribute(localName, namespaceURI?)
getAttributeCount(), getAttributeValue(i)attributeCount(), attributeValue(i)
getAttributeLocalName(i), getAttributePrefix(i), getAttributeNamespace(i), getAttributeType(i)attributeLocalName(i), attributePrefix(i), attributeNamespace(i), attributeType(i)
getAttributeName(i), a QNameattributeName(i), the qualified name as a string
isAttributeSpecified(i)The same
getNamespaceCount(), getNamespacePrefix(i), getNamespaceURI(i)namespaceCount(), namespacePrefix(i), namespaceURI(i)
getPITarget(), getPIData()piTarget(), piData()
getVersion(), getCharacterEncodingScheme(), isStandalone()version(), declaredEncoding(), standalone()
getEncoding()encoding(), the decoder's lower-case name such as utf-8; undefined for a string
getLocation()location()
isStartElement(), isEndElement(), isCharacters()Compare eventType() with EventType
require(…), getTextCharacters(…), getProperty(…)None
NoneskipElement(), which advances from a start tag to its matching end tag

WARNING

attribute(localName, namespaceURI?) takes the local name first, the opposite of StAX's getAttributeValue(namespaceURI, localName). It returns undefined, not null, when the attribute is absent.

Event objects ​

StAXexemplar
nextEvent(), peek(), hasNext(), nextTag()The same; the reader is also iterable with for…of
getElementText()elementText()
event.getEventType(), event.isStartElement()event.type, compared with EventType
event.asStartElement().getName()event.name, after narrowing on event.type
startElement.getAttributeByName(qname)event.attribute(localName, namespaceURI?)
startElement.getAttributes(), getNamespaces()event.attributes, event.namespaces
characters.getData()event.text
event.getLocation()event.location
eventWriter.add(event), add(eventReader)eventWriter.add(event), add(events), addAsync(events)

SAX ​

SAXexemplar
reader.setContentHandler(h), then reader.parse(src)parser.parse(source, handler), parser.parseAsync(source, handler)
startElement(uri, localName, qName, attributes) and the other callbacksThe same names and argument order
characters(char[], start, length)characters(text)
attributes.getValue(uri, localName), getValue(qName), getValue(i)attributes.value(uri, localName), value(qName), value(i)
attributes.getLength(), getLocalName(i), getQName(i), getURI(i), getType(i)attributes.length, localName(i), qName(i), uri(i), type(i)

The stream writer ​

StAX XMLStreamWriterexemplar
writeStartDocument, writeStartElement, writeEmptyElement, writeNamespace, writeDefaultNamespace, writeCharacters, writeCData, writeComment, writeProcessingInstruction, writeEntityRef, writeDTD, writeEndElement, writeEndDocumentThe same names and argument orders
writeAttribute(localName, value), writeAttribute(namespaceURI, localName, value)The same
writeAttribute(prefix, namespaceURI, localName, value)writeAttribute(prefix, localName, namespaceURI, value), the order writeStartElement uses
setPrefix, setDefaultNamespace, flushThe same
getPrefix(uri)prefixOf(uri)
getNamespaceContext().getNamespaceURI(prefix)namespaceOf(prefix)
close()await writer.close()
NonewriteStartElement(qname), writeAttribute(qname, value), taking a QName
NonewriteEndElement(name), which checks the name against the open element
NonewriteNode(node), copy(reader), copyAsync(reader), drain()

Reader settings ​

Settings are typed options on the factory, not feature URIs or property strings. Reader options describes each one.

Javaexemplar option
StAX IS_NAMESPACE_AWARE, JAXP setNamespaceAware, SAX namespacesnamespaceAware
SAX namespace-prefixesnamespacePrefixes
StAX IS_VALIDATING, JAXP setValidating(true), SAX validationvalidator
StAX IS_COALESCING, JAXP setCoalescingcoalescing
StAX IS_REPLACING_ENTITY_REFERENCES, JAXP setExpandEntityReferencesreplaceEntityReferences
StAX IS_SUPPORTING_EXTERNAL_ENTITIES, SAX external-general-entitiessupportExternalEntities
XMLConstants.ACCESS_EXTERNAL_DTDaccessExternalDTD; accessExternalEntities for entities used in content and XInclude targets
Xerces disallow-doctype-decldisallowDoctype
JAXP setXIncludeAware(true)xinclude
SAX EntityResolver2, StAX XMLResolverentityResolver
JAXP URIResolveruriResolver
CatalogManager.catalogResolvercatalog
SAX ErrorHandler, StAX XMLReportererrorHandler
Charset providersdecoders
The jdk.xml limitslimits; see below
DOM check-character-normalizationcheckNormalization
SAX LexicalHandler.startEntity and endEntity; StAX has nonereportEntityBoundaries
Woodstox P_REPORT_PROLOG_WHITESPACEreportPrologWhitespace
Woodstox P_CUSTOM_INTERNAL_ENTITIESentities
SAX resolve-dtd-urisresolveDTDURIs, on SAXParser
SAX xmlns-urisxmlnsURIs, on SAXParser
JAXP setIgnoringCommentsignoringComments, on DocumentBuilder
JAXP setIgnoringElementContentWhitespaceignoringElementContentWhitespace, on DocumentBuilder
NonecheckWellFormedness, copyStrings; missingAttribute, on DocumentBuilder

Writer settings ​

Writer options describes each one.

Javaexemplar option
StAX IS_REPAIRING_NAMESPACESrepairNamespaces
OutputKeys.INDENTindent, set to the indent string
OutputKeys.OMIT_XML_DECLARATIONomitXMLDeclaration
OutputKeys.VERSIONversion
OutputKeys.ENCODINGencoding
OutputKeys.DOCTYPE_PUBLIC, OutputKeys.DOCTYPE_SYSTEMdoctypePublic, doctypeSystem
OutputKeys.CDATA_SECTION_ELEMENTScdataSectionElements
Noneescaping, checkWellFormedness, namespaceAware, suppressIndentation, characterMap

Limits ​

The defaults are those of JDK 24. Limits defines what each counts.

JDK propertyexemplar limit
jdk.xml.entityExpansionLimitentityExpansions
jdk.xml.totalEntitySizeLimittotalEntitySize
jdk.xml.maxGeneralEntitySizeLimitgeneralEntitySize
jdk.xml.maxParameterEntitySizeLimitparameterEntitySize
jdk.xml.entityReplacementLimitentityReferenceNodes
jdk.xml.elementAttributeLimitattributesPerElement
jdk.xml.maxElementDepthelementDepth
jdk.xml.maxXMLNameLimitnameLength

Catalog settings ​

javax.xml.catalog featurecatalogResolver setting
javax.xml.catalog.filesfiles
javax.xml.catalog.preferprefer
javax.xml.catalog.deferdefer
javax.xml.catalog.resolveresolution

Differences you will notice ​

  • Factories are immutable. Every option is passed to the constructor; factory.withOptions(options) returns a copy with those options changed.
  • Nothing external is read by default. accessExternalDTD and accessExternalEntities default to empty, so an external DTD or entity is read only when its protocol is listed and a resolver or catalog supplies it.
  • Recoverable errors are thrown by default. Without an error function in the error handler, a validity error is thrown and parsing stops.
  • Reading a stream does not block. An asynchronous cursor returns EventType.NEED_INPUT from next() when it needs more input, and await reader.fill() supplies it. See Large files and streams.
  • Two more event types. With reportEntityBoundaries on, the cursor reports START_ENTITY and END_ENTITY. A switch over event types should tolerate unknown types.
  • Attribute lookup takes the local name first: attribute(localName, namespaceURI?).
  • The writer's four-argument writeAttribute takes the local name before the namespace:writeAttribute(prefix, localName, namespaceURI, value), the same order as writeStartElement.
  • getAttribute on a DOM element returns null for a missing attribute, as browsers do. Construct the builder with { missingAttribute: 'empty' } for Java's empty string.
  • name() is a string. The cursor's name() and attributeName(i) return the qualified name as written. Event objects carry a QName.
  • Several filters in one call. createFilteredReader(reader, filterA, filterB) applies the filters in order, and createDelegatedReader(reader, new A(), new B()) chains the delegates.
  • A SAX handler is one object. Content, lexical, DTD, declaration and error callbacks are all methods of the same handler, which is passed to parse.
  • Builders also accept a reader. DocumentBuilder.parse(reader), XdmDocumentBuilder.parse(reader) and SAXParser.parse(reader, handler) start at the reader's current position. See One record at a time.
  • Locations report where an event starts, not where it ends as the JDK's do. Lines and columns count from 1, and columns count UTF-16 code units, as JavaScript strings do.
  • hasNext() is false once a reader has failed, so a loop over a malformed document terminates after the error.
  • The writer writes <a/> for an element with no content, whether it was written with writeEmptyElement or with writeStartElement followed immediately by writeEndElement.
  • The writer escapes more by default, so that the output round-trips: parsing it returns exactly the text written. Set escaping: 'minimal' for less.
  • Closing a writer is asynchronous when the destination is a stream: await writer.close().
  • Names follow the current edition of XML 1.0, which allows more characters in names than the JDK's parser accepts.
  • An enumerated attribute's type is reported as NMTOKEN, as SAX reports it.

Released under the Apache License 2.0.