XML

suggest change

XML is still everywhere: RSS and Atom feeds, sitemaps, SOAP services, Maven POMs, Android layouts, Office files and many enterprise APIs.

Kotlin on the JVM has three main ways to work with it:

This article covers:

For HTML, which is usually not well-formed XML, use jsoup as shown in Parsing HTML.

Parsing with DOM

DocumentBuilderFactory parses XML into a Document. The DOM API is old: NodeList isn't Iterable, a missing attribute is "" instead of null, and child nodes include whitespace text. A few extension functions make it pleasant to use from Kotlin:

import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import javax.xml.parsers.DocumentBuilderFactory

// NodeList is not Iterable; make it usable with for loops and map
fun NodeList.elements(): List<Element> =
    (0 until length).map { item(it) }.filterIsInstance<Element>()

fun Element.children(name: String): List<Element> =
    childNodes.elements().filter { it.tagName == name }

fun Element.child(name: String): Element? = children(name).firstOrNull()

fun Element.text(name: String): String? = child(name)?.textContent?.trim()

fun main() {
    val xml = """
        <?xml version="1.0" encoding="UTF-8"?>
        <library name="City &amp; County">
          <!-- fiction section -->
          <book id="b1" available="true">
            <title>Dune</title>
            <author>Frank Herbert</author>
            <year>1965</year>
            <price currency="USD">9.99</price>
          </book>
          <book id="b2" available="false">
            <title><![CDATA[Tom & Jerry <Classic>]]></title>
            <author>Various</author>
            <year>1940</year>
          </book>
        </library>
    """.trimIndent()

    val factory = DocumentBuilderFactory.newInstance()
    val doc = factory.newDocumentBuilder().parse(xml.byteInputStream())
    val root = doc.documentElement
    root.normalize()

    println("root: ${root.tagName}, name=${root.getAttribute("name")}")

    for (book in root.children("book")) {
        val id = book.getAttribute("id")
        val available = book.getAttribute("available").toBoolean()
        val title = book.text("title")
        val year = book.text("year")?.toInt()
        val price = book.child("price")
        val priceText = price?.let { "${it.textContent} ${it.getAttribute("currency")}" } ?: "n/a"
        println("$id: $title ($year) available=$available price=$priceText")
    }

    // getElementsByTagName searches the whole subtree
    val authors = doc.getElementsByTagName("author").elements().map { it.textContent }
    println(authors)

    // a missing attribute is an empty string, not null
    val b1 = root.children("book").first()
    println("missing attr: '${b1.getAttribute("isbn")}' has=${b1.hasAttribute("isbn")}")

    // child nodes include whitespace text and comments
    val kinds = root.childNodes.let { nl -> (0 until nl.length).map { nl.item(it).nodeType } }
    println(kinds.groupingBy {
        when (it) {
            Node.ELEMENT_NODE -> "element"
            Node.TEXT_NODE -> "text"
            Node.COMMENT_NODE -> "comment"
            else -> "other"
        }
    }.eachCount())
}

Output:

root: library, name=City & County
b1: Dune (1965) available=true price=9.99 USD
b2: Tom & Jerry <Classic> (1940) available=false price=n/a
[Frank Herbert, Various]
missing attr: '' has=false
{text=4, comment=1, element=2}

Things to note:

XPath and namespaces

XPath selects nodes with path expressions, which is often shorter than walking the tree. The catch is namespaces. Many real documents (Atom, SOAP, SVG, Maven POMs) declare a default namespace with xmlns="...". In a namespace-aware document, /feed/title then matches nothing. You must bind a prefix to the namespace URI and use it in the expression:

import org.w3c.dom.Document
import org.w3c.dom.NodeList
import javax.xml.XMLConstants
import javax.xml.namespace.NamespaceContext
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathFactory

val xml = """
    <feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
      <title>Kotlin News</title>
      <entry>
        <title>Kotlin 2.4 released</title>
        <link href="https://example.com/kotlin-2-4"/>
        <media:thumbnail url="https://example.com/k24.png" width="120"/>
        <updated>2026-09-01T10:00:00Z</updated>
      </entry>
      <entry>
        <title>Coroutines tips</title>
        <link href="https://example.com/coroutines"/>
        <updated>2026-08-15T08:30:00Z</updated>
      </entry>
    </feed>
""".trimIndent()

fun parse(text: String, namespaceAware: Boolean): Document {
    val f = DocumentBuilderFactory.newInstance()
    f.isNamespaceAware = namespaceAware
    return f.newDocumentBuilder().parse(text.byteInputStream())
}

class Prefixes(private val map: Map<String, String>) : NamespaceContext {
    override fun getNamespaceURI(prefix: String) = map[prefix] ?: XMLConstants.NULL_NS_URI
    override fun getPrefix(uri: String) = map.entries.find { it.value == uri }?.key
    override fun getPrefixes(uri: String) = listOfNotNull(getPrefix(uri)).iterator()
}

fun main() {
    val doc = parse(xml, namespaceAware = true)
    val xpath = XPathFactory.newInstance().newXPath()

    // without a namespace context, elements in the Atom namespace don't match
    println("no ns: '${xpath.evaluate("/feed/title", doc)}'")

    xpath.namespaceContext = Prefixes(
        mapOf("a" to "http://www.w3.org/2005/Atom", "media" to "http://search.yahoo.com/mrss/")
    )

    println(xpath.evaluate("/a:feed/a:title", doc))
    println(xpath.evaluate("count(//a:entry)", doc, XPathConstants.NUMBER))
    println(xpath.evaluate("//a:entry[1]/media:thumbnail/@url", doc))
    println(xpath.evaluate("//a:entry[a:title='Coroutines tips']/a:link/@href", doc))
    println(xpath.evaluate("boolean(//a:entry[2]/media:thumbnail)", doc, XPathConstants.BOOLEAN))

    // compile once, evaluate many times
    val titles = xpath.compile("//a:entry/a:title/text()")
    val nodes = titles.evaluate(doc, XPathConstants.NODESET) as NodeList
    println((0 until nodes.length).map { nodes.item(it).nodeValue })

    // local-name() ignores namespaces, handy for quick scripts
    val doc2 = parse(xml, namespaceAware = false)
    val xp2 = XPathFactory.newInstance().newXPath()
    println(xp2.evaluate("//*[local-name()='thumbnail']/@width", doc))
    println(xp2.evaluate("/feed/entry[2]/updated", doc2))
}

Output:

no ns: ''
Kotlin News
2.0
https://example.com/k24.png
https://example.com/coroutines
false
[Kotlin 2.4 released, Coroutines tips]
120
2026-08-15T08:30:00Z

Secure parsing

XML has a dangerous feature: a <!DOCTYPE> can define entities that read local files or URLs (XML External Entity, XXE), or that expand exponentially ("billion laughs"). The JDK's default factory resolves external entities. Never parse untrusted XML with the defaults:

import javax.xml.XMLConstants
import javax.xml.parsers.DocumentBuilderFactory
import kotlin.io.path.createTempFile
import kotlin.io.path.deleteIfExists
import kotlin.io.path.writeText

fun secureFactory(): DocumentBuilderFactory = DocumentBuilderFactory.newInstance().apply {
    // reject any <!DOCTYPE>; this blocks XXE and entity-expansion attacks
    setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
    setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)
    setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "")
    setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "")
    isXIncludeAware = false
    isExpandEntityReferences = false
}

fun main() {
    val secret = createTempFile("secret", ".txt")
    secret.writeText("db-password=hunter2")

    val evil = """
        <?xml version="1.0"?>
        <!DOCTYPE order [ <!ENTITY x SYSTEM "${secret.toUri()}"> ]>
        <order><note>&x;</note></order>
    """.trimIndent()

    val unsafe = DocumentBuilderFactory.newInstance().newDocumentBuilder()
    val doc = unsafe.parse(evil.byteInputStream())
    println("default factory: ${doc.documentElement.textContent}")

    try {
        val builder = secureFactory().newDocumentBuilder()
        builder.setErrorHandler(null) // don't print "[Fatal Error]" to stderr
        builder.parse(evil.byteInputStream())
    } catch (e: Exception) {
        println("secure factory: ${e::class.simpleName}: ${e.message}")
    }

    val ok = secureFactory().newDocumentBuilder().parse("<order><note>hi</note></order>".byteInputStream())
    println("normal document: ${ok.documentElement.textContent}")
    secret.deleteIfExists()
}

Output:

default factory: db-password=hunter2
secure factory: SAXParseException: DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
normal document: hi

The default parser copied the contents of a local file into the document. If your server echoes parsed values back, or puts them in error messages, an attacker can read any file the process can read.

Disallowing DOCTYPE is the simplest fix and works for almost all data formats. If you have to accept documents with a DTD, keep disallow-doctype-decl off but turn off http://xml.org/sax/features/external-general-entities and external-parameter-entities instead. The same applies to SAXParserFactory, TransformerFactory, SchemaFactory and XMLInputFactory. The StAX example below shows the settings for XMLInputFactory.

Building and pretty-printing a document

To create XML with DOM, build elements with Document.createElement() and write the tree with a Transformer. The DOM escapes <, & and quotes for you:

import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.StringWriter
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.OutputKeys
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult

data class Item(val sku: String, val name: String, val qty: Int, val price: String)

// small helper: create a child element with attributes and optional text
fun Element.add(name: String, text: String? = null, vararg attrs: Pair<String, String>): Element {
    val e = ownerDocument.createElement(name)
    for ((k, v) in attrs) e.setAttribute(k, v)
    if (text != null) e.textContent = text
    appendChild(e)
    return e
}

fun Document.toXmlString(indent: Boolean = true): String {
    val t = TransformerFactory.newInstance().newTransformer()
    // the JDK writes no newline after <?xml ...?>, so we write the declaration ourselves
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")
    if (indent) {
        t.setOutputProperty(OutputKeys.INDENT, "yes")
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
    }
    val out = StringWriter()
    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
    t.transform(DOMSource(this), StreamResult(out))
    return out.toString()
}

fun main() {
    val items = listOf(
        Item("A-1", "Coffee \"Arabica\" 1kg", 2, "18.50"),
        Item("B-7", "Mugs <set of 4> & spoons", 1, "24.00"),
    )

    val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
    val order = doc.createElement("order")
    order.setAttribute("id", "1001")
    doc.appendChild(order)

    order.appendChild(doc.createComment(" generated "))
    order.add("customer", "Zoë O'Brien", "email" to "zoe@example.com")
    val list = order.add("items")
    for (it in items) {
        list.add("item", it.name, "sku" to it.sku, "qty" to it.qty.toString(), "price" to it.price)
    }
    order.add("note").appendChild(doc.createCDATASection("Leave at door <back>"))

    print(doc.toXmlString())
    println(doc.toXmlString(indent = false).length)
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<order id="1001">
  <!-- generated -->
  <customer email="zoe@example.com">Zoë O'Brien</customer>
  <items>
    <item price="18.50" qty="2" sku="A-1">Coffee "Arabica" 1kg</item>
    <item price="24.00" qty="1" sku="B-7">Mugs &lt;set of 4&gt; &amp; spoons</item>
  </items>
  <note><![CDATA[Leave at door <back>]]></note>
</order>
342

Streaming large files with StAX

StAX (javax.xml.stream) is a pull parser. You call next() and get one event at a time: start element, text, end element. Memory use stays flat no matter how big the file is. XMLStreamWriter is the matching streaming writer.

Wrapping the reader in a sequence {} gives you a lazy Sequence of objects:

import java.nio.file.Path
import javax.xml.stream.XMLInputFactory
import javax.xml.stream.XMLOutputFactory
import javax.xml.stream.XMLStreamConstants.END_ELEMENT
import javax.xml.stream.XMLStreamConstants.START_ELEMENT
import javax.xml.stream.XMLStreamReader
import kotlin.io.path.createTempFile
import kotlin.io.path.deleteIfExists
import kotlin.io.path.fileSize
import kotlin.io.path.inputStream
import kotlin.io.path.outputStream

data class Sale(val id: Int, val region: String, val amount: Double)

// write a large file one element at a time, without building a tree
fun writeSales(path: Path, count: Int) {
    path.outputStream().buffered().use { os ->
        val w = XMLOutputFactory.newInstance().createXMLStreamWriter(os, "UTF-8")
        w.writeStartDocument("UTF-8", "1.0")
        w.writeStartElement("sales")
        val regions = listOf("north", "south", "east", "west")
        for (i in 1..count) {
            w.writeStartElement("sale")
            w.writeAttribute("id", i.toString())
            w.writeStartElement("region")
            w.writeCharacters(regions[i % 4])
            w.writeEndElement()
            w.writeStartElement("amount")
            w.writeCharacters("%.2f".format(java.util.Locale.ROOT, (i % 100) * 1.25))
            w.writeEndElement()
            w.writeEndElement()
        }
        w.writeEndElement()
        w.writeEndDocument()
        w.close() // flushes; does not close the underlying stream
    }
}

// read one <sale> element; the reader is positioned on its START_ELEMENT
fun readSale(r: XMLStreamReader): Sale {
    val id = r.getAttributeValue(null, "id").toInt()
    var region = ""
    var amount = 0.0
    while (r.next() != END_ELEMENT || r.localName != "sale") {
        if (r.eventType == START_ELEMENT) {
            when (r.localName) {
                "region" -> region = r.elementText   // reads text and moves to END_ELEMENT
                "amount" -> amount = r.elementText.toDouble()
            }
        }
    }
    return Sale(id, region, amount)
}

fun readSales(path: Path): Sequence<Sale> = sequence {
    path.inputStream().buffered().use { input ->
        val factory = XMLInputFactory.newInstance().apply {
            setProperty(XMLInputFactory.SUPPORT_DTD, false)
            setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false)
        }
        val r = factory.createXMLStreamReader(input)
        try {
            while (r.hasNext()) {
                if (r.next() == START_ELEMENT && r.localName == "sale") yield(readSale(r))
            }
        } finally {
            r.close()
        }
    }
}

fun main() {
    val path = createTempFile("sales", ".xml")
    writeSales(path, 200_000)
    println("file size: ${path.fileSize() / 1024} KB")

    println(readSales(path).take(3).toList())

    val totals = readSales(path)
        .groupingBy { it.region }
        .fold(0.0) { acc, s -> acc + s.amount }
    for ((region, total) in totals.toSortedMap()) println("$region: %.2f".format(total))

    path.deleteIfExists()
}

Output:

file size: 13293 KB
[Sale(id=1, region=south, amount=1.25), Sale(id=2, region=east, amount=2.5), Sale(id=3, region=west, amount=3.75)]
east: 3125000.00
north: 3000000.00
south: 3062500.00
west: 3187500.00

A small DSL for writing XML

XMLStreamWriter calls must be balanced by hand. Kotlin lambdas with receivers can give it structure, in the same style as the type-safe builders. Here is a sitemap generator:

import java.io.StringWriter
import javax.xml.stream.XMLOutputFactory
import javax.xml.stream.XMLStreamWriter

@DslMarker
annotation class XmlDsl

@XmlDsl
class Tag(private val w: XMLStreamWriter) {
    fun attr(name: String, value: Any) = w.writeAttribute(name, value.toString())
    fun namespace(uri: String) = w.writeDefaultNamespace(uri)
    fun text(value: Any) = w.writeCharacters(value.toString())

    fun tag(name: String, text: Any? = null, body: Tag.() -> Unit = {}) {
        w.writeStartElement(name)
        Tag(w).body()               // attributes must come before any content
        if (text != null) w.writeCharacters(text.toString())
        w.writeEndElement()
    }
}

fun xml(root: String, body: Tag.() -> Unit): String {
    val out = StringWriter()
    val w = XMLOutputFactory.newInstance().createXMLStreamWriter(out)
    w.writeStartDocument("UTF-8", "1.0")
    Tag(w).tag(root, body = body)
    w.writeEndDocument()
    w.close()
    return out.toString()
}

data class Url(val loc: String, val lastmod: String, val priority: Double)

fun main() {
    val urls = listOf(
        Url("https://example.com/", "2026-10-01", 1.0),
        Url("https://example.com/search?q=kotlin&page=2", "2026-09-20", 0.5),
    )

    val sitemap = xml("urlset") {
        namespace("http://www.sitemaps.org/schemas/sitemap/0.9")
        for (u in urls) {
            tag("url") {
                tag("loc", u.loc)
                tag("lastmod", u.lastmod)
                tag("priority", u.priority)
            }
        }
    }
    println(sitemap)
}

Output:

<?xml version='1.0' encoding='UTF-8'?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://example.com/</loc><lastmod>2026-10-01</lastmod><priority>1.0</priority></url><url><loc>https://example.com/search?q=kotlin&amp;page=2</loc><lastmod>2026-09-20</lastmod><priority>0.5</priority></url></urlset>

Elements can't be left unclosed, the writer escapes & in the URL, and ordinary Kotlin for and if work inside the builder. @DslMarker stops an inner block from calling attr() on an outer tag by accident. Because the writer streams, this works for very large documents too: pass a file's OutputStream instead of a StringWriter.

Data binding with xmlutil

Mapping XML to data classes by hand gets tedious. xmlutil does it with kotlinx.serialization. It needs the serialization compiler plugin:

plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21"
}

dependencies {
    implementation("io.github.pdvrieze.xmlutil:serialization:1.0.2")
}

XML has attributes, elements and text, while JSON has only fields, so xmlutil follows rules to decide where each property goes:

import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import nl.adaptivity.xmlutil.XmlDeclMode
import nl.adaptivity.xmlutil.core.XmlVersion
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.serialization.XmlChildrenName
import nl.adaptivity.xmlutil.serialization.XmlElement
import nl.adaptivity.xmlutil.serialization.XmlSerialName
import nl.adaptivity.xmlutil.serialization.XmlValue

@Serializable
@XmlSerialName("price")
data class Price(
    val currency: String,             // primitive -> attribute by default
    @XmlValue val amount: Double,     // text content of <price>
)

@Serializable
@XmlSerialName("book")
data class Book(
    val id: String,
    @XmlElement val title: String,    // force a child element instead of an attribute
    @XmlElement val year: Int,
    val price: Price? = null,         // class -> child element
    @OptIn(ExperimentalSerializationApi::class)
    @EncodeDefault(EncodeDefault.Mode.NEVER)
    @XmlElement
    @XmlChildrenName("tag")
    val tags: List<String> = emptyList(),
)

@Serializable
@XmlSerialName("library")
data class Library(
    val name: String,
    val books: List<Book>,            // list of classes -> repeated <book> elements
)

val xml = XML.v1 {
    indentString = "  "
    xmlVersion = XmlVersion.XML10
    xmlDeclMode = XmlDeclMode.Charset
}

fun main() {
    val lib = Library(
        name = "City & County",
        books = listOf(
            Book("b1", "Dune", 1965, Price("USD", 9.99), listOf("sci-fi", "classic")),
            Book("b2", "Tom & Jerry <Classic>", 1940),
        ),
    )

    val text = xml.encodeToString(Library.serializer(), lib)
    println(text)

    val back = xml.decodeFromString(Library.serializer(), text)
    println(back == lib)
    println(back.books[0])

    val input = """
        <library name="Branch 2">
          <book id="b9">
            <year>2008</year>
            <title>Kotlin in Action</title>
          </book>
        </library>
    """.trimIndent()
    println(xml.decodeFromString(Library.serializer(), input))
}

Output:

<?xml version='1.0' encoding='UTF-8' ?>
<library name="City &amp; County">
  <book id="b1">
    <title>Dune</title>
    <year>1965</year>
    <price currency="USD">9.99</price>
    <tags>
      <tag>sci-fi</tag>
      <tag>classic</tag>
    </tags>
  </book>
  <book id="b2">
    <title>Tom &amp; Jerry &lt;Classic&gt;</title>
    <year>1940</year>
  </book>
</library>
true
Book(id=b1, title=Dune, year=1965, price=Price(currency=USD, amount=9.99), tags=[sci-fi, classic])
Library(name=Branch 2, books=[Book(id=b9, title=Kotlin in Action, year=2008, price=null, tags=[])])

Namespaces, unknown content and errors

@XmlSerialName(name, namespace, prefix) puts an element in a namespace:

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import nl.adaptivity.xmlutil.XmlDeclMode
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.serialization.XmlElement
import nl.adaptivity.xmlutil.serialization.XmlSerialName

const val NS = "urn:example:shop"

@Serializable
@XmlSerialName("item", NS, "s")
data class Item(
    val sku: String,
    @XmlSerialName("qty") val quantity: Int,
    @XmlElement @XmlSerialName("name", NS, "s") val name: String,
)

@Serializable
@XmlSerialName("order", NS, "s")
data class Order(
    val id: Int,
    @XmlElement(false) @SerialName("status") val state: Status = Status.NEW,
    val items: List<Item>,
)

enum class Status { NEW, PAID, SHIPPED }

fun main() {
    val xml = XML.v1 {
        indentString = "  "
        xmlDeclMode = XmlDeclMode.None
    }
    val order = Order(7, Status.PAID, listOf(Item("A-1", 2, "Coffee"), Item("B-7", 1, "Mugs")))
    val text = xml.encodeToString(Order.serializer(), order)
    println(text)

    // the prefix doesn't matter when decoding, only the namespace URI
    val other = """
        <order xmlns="urn:example:shop" id="8">
          <item sku="C-3" qty="5"><name>Tea</name></item>
        </order>
    """.trimIndent()
    println(xml.decodeFromString(Order.serializer(), other))

    // unknown content is an error by default
    val extra = """
        <s:order xmlns:s="urn:example:shop" id="9" priority="high">
          <s:item sku="D-1" qty="1"><s:name>Jam</s:name><s:color>red</s:color></s:item>
        </s:order>
    """.trimIndent()
    try {
        xml.decodeFromString(Order.serializer(), extra)
    } catch (e: Exception) {
        println("${e::class.simpleName}: ${e.message?.lines()?.first()}")
    }

    val lenient = XML.v1 {
        policy { ignoreUnknownChildren() }
    }
    println(lenient.decodeFromString(Order.serializer(), extra))

    // wrong data type
    try {
        xml.decodeFromString(Order.serializer(), other.replace("qty=\"5\"", "qty=\"five\""))
    } catch (e: Exception) {
        println("${e::class.simpleName}: ${e.message?.lines()?.first()}")
    }
}

Output:

<s:order xmlns:s="urn:example:shop" id="7" status="PAID">
  <s:item sku="A-1" qty="2">
    <s:name>Coffee</s:name>
  </s:item>
  <s:item sku="B-7" qty="1">
    <s:name>Mugs</s:name>
  </s:item>
</s:order>
Order(id=8, state=NEW, items=[Item(sku=C-3, quantity=5, name=Tea)])
UnknownXmlFieldException: Serialization exception at [1:60]: Could not find a field for name (Order) {urn:example:shop}order/priority (Attribute)
Order(id=9, state=NEW, items=[Item(sku=D-1, quantity=1, name=Jam)])
XmlParsingException: Invalid XML value at position: 2:3: For input string: "five"

Jackson XML

If your project already uses Jackson for JSON, its XML module maps plain classes with no compiler plugin. Jackson 3 uses the tools.jackson group:

dependencies {
    implementation("tools.jackson.dataformat:jackson-dataformat-xml:3.2.3")
    implementation("tools.jackson.module:jackson-module-kotlin:3.2.3")
}

Jackson writes every property as an element by default. Annotate attributes and text, and configure list wrapping:

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonRootName
import tools.jackson.databind.JsonNode
import tools.jackson.databind.SerializationFeature
import tools.jackson.dataformat.xml.XmlMapper
import tools.jackson.dataformat.xml.XmlWriteFeature
import tools.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import tools.jackson.dataformat.xml.annotation.JacksonXmlProperty
import tools.jackson.dataformat.xml.annotation.JacksonXmlText
import tools.jackson.module.kotlin.kotlinModule
import tools.jackson.module.kotlin.readValue

data class Price(
    @JacksonXmlProperty(isAttribute = true) val currency: String,
    @JacksonXmlText val amount: Double,
)

data class Book(
    @JacksonXmlProperty(isAttribute = true) val id: String,
    val title: String,
    val year: Int,
    val price: Price? = null,
    @JacksonXmlElementWrapper(localName = "tags")
    @JacksonXmlProperty(localName = "tag")
    val tags: List<String> = emptyList(),
)

@JsonRootName("library")
data class Library(
    @JacksonXmlProperty(isAttribute = true) val name: String,
    @JacksonXmlElementWrapper(useWrapping = false)   // <book> elements directly under <library>
    @JacksonXmlProperty(localName = "book")
    val books: List<Book>,
)

val mapper: XmlMapper = XmlMapper.builder()
    .addModule(kotlinModule())
    .enable(SerializationFeature.INDENT_OUTPUT)
    .enable(XmlWriteFeature.WRITE_XML_DECLARATION)
    // skip nulls and empty lists instead of writing xsi:nil and <tags/>
    .changeDefaultPropertyInclusion { it.withValueInclusion(JsonInclude.Include.NON_EMPTY) }
    .build()

fun main() {
    val lib = Library(
        "City & County",
        listOf(
            Book("b1", "Dune", 1965, Price("USD", 9.99), listOf("sci-fi", "classic")),
            Book("b2", "Tom & Jerry <Classic>", 1940),
        ),
    )
    val text = mapper.writeValueAsString(lib)
    print(text)

    val back = mapper.readValue<Library>(text)
    println(back == lib)

    // unknown elements are ignored by default in Jackson 3
    val input = """
        <library name="Branch 2">
          <book id="b9"><title>Kotlin in Action</title><year>2008</year><isbn>123</isbn></book>
        </library>
    """.trimIndent()
    println(mapper.readValue<Library>(input))

    // untyped tree: attributes and child elements both become fields
    val tree: JsonNode = mapper.readTree(input)
    println(tree)
    println(tree.at("/book/title").asString())
}

Output:

<?xml version='1.0' encoding='UTF-8'?>
<library name="City &amp; County">
  <book id="b1">
    <title>Dune</title>
    <year>1965</year>
    <price currency="USD">9.99</price>
    <tags>
      <tag>sci-fi</tag>
      <tag>classic</tag>
    </tags>
  </book>
  <book id="b2">
    <title>Tom &amp; Jerry &lt;Classic></title>
    <year>1940</year>
  </book>
</library>
true
Library(name=Branch 2, books=[Book(id=b9, title=Kotlin in Action, year=2008, price=null, tags=[])])
{"name":"Branch 2","book":{"id":"b9","title":"Kotlin in Action","year":"2008","isbn":"123"}}
Kotlin in Action

Gotchas

A few problems come up again and again:

import tools.jackson.dataformat.xml.XmlMapper
import javax.xml.parsers.DocumentBuilderFactory

fun String.escapeXml(): String = buildString(length) {
    for (c in this@escapeXml) {
        when (c) {
            '<' -> append("&lt;")
            '>' -> append("&gt;")
            '&' -> append("&amp;")
            '"' -> append("&quot;")
            '\'' -> append("&apos;")
            else -> append(c)
        }
    }
}

fun isWellFormed(xml: String): Boolean = try {
    val b = DocumentBuilderFactory.newInstance().newDocumentBuilder()
    b.setErrorHandler(null)
    b.parse(xml.byteInputStream())
    true
} catch (e: Exception) {
    println("  ${e.message}")
    false
}

fun main() {
    val name = "Ben & Jerry's \"<Cookie Dough>\""

    val bad = "<product name=\"$name\"/>"
    println(bad)
    println(isWellFormed(bad))

    val good = "<product name=\"${name.escapeXml()}\"/>"
    println(good)
    println(isWellFormed(good))

    // one child element vs. several: the untyped tree changes shape
    val mapper = XmlMapper()
    println(mapper.readTree("<cart><item>a</item></cart>"))
    println(mapper.readTree("<cart><item>a</item><item>b</item></cart>"))

    // text that only looks empty
    val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        .parse("<a>\n  <b>x</b>\n</a>".byteInputStream())
    println(doc.documentElement.firstChild.nodeName)
    println("'" + doc.documentElement.textContent + "'")
}

Output:

<product name="Ben & Jerry's "<Cookie Dough>""/>
  The entity name must immediately follow the '&' in the entity reference.
false
<product name="Ben &amp; Jerry&apos;s &quot;&lt;Cookie Dough&gt;&quot;"/>
true
{"item":"a"}
{"item":["a","b"]}
#text
'
  x
'

Which API to use?

Task Use
Read a few values from a small document DOM + XPath
Untrusted input Any parser, with DOCTYPE disabled
Files larger than tens of MB StAX (XMLStreamReader)
Generate large files StAX (XMLStreamWriter), optionally with a DSL
Map XML to data classes, multiplatform xmlutil
Map XML to data classes in a Jackson project Jackson XML
HTML or broken markup jsoup

For a new Kotlin project that exchanges XML with an API, start with xmlutil or Jackson for the data classes, and fall back to StAX for the one huge file that doesn't fit in memory.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents