A streaming XML parser for Kotlin Multiplatform (JVM, JS).
Emits a flat stream of events (StartElement, EndElement, Text, CData,
Comment, ProcessingInstruction) while tokenizing XML input, without
building an in-memory document until you ask for one. Designed for
incremental / push-based parsing where input arrives in chunks.
XmlParser is the low-level, non-suspending parser. You push byte chunks
into it and pull events out:
val p = XmlParser()
p.push("""<root a="1">hello</root>""".encodeToByteArray())
p.finish()
while (true) {
val event = p.next() ?: break
when (event) {
is XmlEvent.StartElement -> println("start ${event.name.localName}")
is XmlEvent.EndElement -> println("end ${event.name.localName}")
is XmlEvent.Text -> println("text ${event.text}")
is XmlEvent.InProgress -> { /* need more data -- call push() */ }
else -> {}
}
}Input can be fed incrementally. When the parser needs more data it returns
XmlEvent.InProgress. Push another chunk and continue calling next():
val p = XmlParser()
p.push(firstChunk)
while (true) {
val event = p.next()!!
if (event is XmlEvent.InProgress) break
handle(event)
}
p.push(secondChunk)
p.finish()
while (true) {
val event = p.next() ?: break
handle(event)
}push() copies the selected byte range, so the caller may reuse the buffer.
Text runs may be split arbitrarily, both by the underlying parser and by
chunk boundaries; concatenate consecutive XmlEvent.Text events if you need
the complete character data of an element.
next() returns null only when the whole document has been parsed
successfully, and XmlEvent.InProgress when the current chunk has been
consumed and more input is required -- push the next chunk and call next()
again.
finish() marks the end of the input and may be called more than once;
repeated calls are a no-op. Calling next() after finish() while the parser
still waits for input raises XmlParseException, so null always means the
document was complete.
Malformed input raises XmlParseException; its byteOffset is the offset of
the first byte that could not be accepted, with optional line / column
information. push() after finish() raises IllegalStateException.
The parser is strict about XML well-formedness, as enforced by the platform
backend. close() releases backend resources; call it if you stop before the
end of the document. The JS backend needs it to release WASM memory.
InProgress-- buffer exhausted, push more data (XmlParseronly)StartElement-- element name, attributes, namespace declarationsEndElement-- element nameText-- character dataCData-- CDATA section contentComment-- comment contentProcessingInstruction--targetanddata
Names are carried as XmlName(localName, namespaceUri, prefix). namespaceUri
and prefix are null for unqualified names; a name in the default namespace
has a namespaceUri but no prefix. Attributes are XmlAttribute(name, value)
and namespace declarations are XmlNamespace(prefix, uri) (the default
namespace uses an empty prefix). Namespace declarations are reported on the
corresponding StartElement; it is up to the consumer to track scopes.
The parser exposes the XML declaration through version and encoding.
encoding is null when the document did not declare one; both backends
auto-detect the actual byte encoding.
SuspendingXmlParser wraps XmlParser and reads from a Ktor
ByteReadChannel. It automatically feeds the underlying parser when it needs
more data, and never reports XmlEvent.InProgress. The channel stays owned
by the caller: the parser does not close or cancel it, not even on errors.
val parser = SuspendingXmlParser(byteReadChannel)
while (true) {
val event = parser.next() ?: break
when (event) {
is XmlEvent.StartElement -> println(event.name.localName)
else -> {}
}
}Convenience methods:
expect<T>()returns the next event and fails if it has another type.skipElement()skips the next element and everything nested below it.nextElement()builds anXmlElementtree for the next element.
val root: XmlElement = parser.nextElement()
println(root.name.localName)XmlElement and the other XmlNode types (XmlText, XmlCData,
XmlComment, XmlProcessingInstruction) preserve mixed content and document
order, including whitespace.
Combine next() with skipElement() to efficiently extract specific fields
from large XML without materializing the whole document:
val parser = SuspendingXmlParser(channel)
parser.expect<XmlEvent.StartElement>()
while (true) {
when (val event = parser.next()) {
is XmlEvent.StartElement -> {
if (event.name.localName == "target") {
val value = parser.nextElement()
// use value
} else {
parser.skipElement()
}
}
is XmlEvent.EndElement -> break
null -> break
else -> {}
}
}- JVM
- JS (Node.js, and browsers through a bundler)
The JS artefact is an ES module, because expat-wasm is ESM-only.
WasmJS is planned but not part of the initial release; see issue #1.
kotlinx-coroutines-coreio.ktor:ktor-io- JVM:
com.fasterxml:aalto-xml - JS:
expat-wasm(npm)
Versions are pinned in build.gradle.kts.
- The JVM backend does not expand custom general entities declared in a DTD; expat does. See issue #2.
- DTD declarations are parsed and skipped, not surfaced as events.
- The Aalto async scanner rejects an internal DTD subset without
SYSTEM/PUBLIC; aSYSTEMidentifier works on both backends.
./gradlew buildEnable the versioned git hooks once per checkout:
./gradlew installGitHooksThe pre-commit hook refuses to commit while projectVersion in
gradle.properties matches an existing v<version> tag, so a version is not
reused after it has been released.
./gradlew jvmTest and ./gradlew jsTest run the common test suite on each
platform.
The version lives in gradle.properties as projectVersion. After
./gradlew publishToMavenLocal, src/jvmTest/kotlin/publish.kt -v<version>
collects the artefacts into publish.zip; the -javadoc.jar it ships is an
empty stub, so no documentation generator is configured.
See LICENSE for details.