XML
suggest changeXML 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:
- The JDK built-ins in
javax.xmlandorg.w3c.dom. DOM loads the whole document into a tree, XPath queries that tree, and StAX streams through large files one event at a time. They need no dependencies, but the APIs are Java-style and verbose. - xmlutil adds XML support to kotlinx.serialization. You map XML to
@Serializabledata classes. It works on JVM, Android, JS and Native. - Jackson XML with the Kotlin module. Use it if your project already uses Jackson for JSON.
This article covers:
- parsing with DOM and small Kotlin helpers
- XPath queries and namespaces
- secure parsing (XXE)
- building and pretty-printing documents
- streaming large files with StAX
- a small Kotlin DSL for writing XML
- data binding with xmlutil and Jackson
- common gotchas
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 & 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:
- The parser decodes entities (
&) and CDATA sections, sotextContentgives you the plain text. textContentof an element includes the text of all its descendants. Use it on leaf elements.parse()also accepts aFile, anInputStreamor a URI string. Pass bytes or a stream rather than aReaderso the parser can use the encoding from the<?xml?>declaration.DocumentBuilderFactoryandDocumentBuilderare not thread-safe. Create a builder per thread or per parse.- DOM keeps the whole document in memory, typically several times the file size. For files over a few tens of MB, use StAX (shown below).
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
evaluate(expr, node)returns aString: the text of the first match, or""if nothing matches. PassXPathConstants.NUMBER,BOOLEAN,NODEorNODESETto get other result types.NUMBERis always aDouble.- The prefix in the XPath expression (
a:) doesn't need to match the prefix in the document. Only the namespace URI matters. DocumentBuilderFactoryis not namespace-aware by default. Then/feed/entrymatches by the literal tag name. That works for quick scripts, but breaks if a producer switches from a default namespace to a prefix such as<atom:feed>.XPathobjects are not thread-safe. Compile expressions once per thread if you evaluate them in a hot loop.
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 <set of 4> & spoons</item>
</items>
<note><![CDATA[Leave at door <back>]]></note>
</order>
342
- The JDK's serializer sorts attributes alphabetically. XML doesn't give attribute order any meaning, so parsers don't care.
- Without
indent-amount,INDENT=yesadds line breaks but no indentation. - Indented output uses the platform line separator, so you get
\r\non Windows. - To write to a file, use
StreamResult(path.toFile()). Then the transformer encodes the bytes in UTF-8 (or whateverOutputKeys.ENCODINGsays). - Don't build XML with string templates. A value with
&or<produces a broken document. See the gotchas section.
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
take(3)stops parsing after the third<sale>, but it also leaves the file open. When you stop iterating asequence {}early, the code after the lastyieldnever runs, and that includesfinallyanduse. Consume such sequences fully, or pass a callback (forEachSale(path) { ... }) so the function that opens the stream also closes it.elementTextreads all text of a text-only element and leaves the reader on its end tag. It throws if the element contains child elements.XMLStreamWriterdoesn't indent. Its output is one long line, which is fine for machine-to-machine files.getAttributeValue(null, "id")matches the attribute in any namespace. Pass a namespace URI to be exact.- The
SUPPORT_DTD = falsesetting is the StAX equivalent of disallowingDOCTYPE.
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&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:
- A primitive property (
String,Int, enum...) becomes an attribute. Add@XmlElementto make it a child element. - A class property becomes a child element, named after the class's
@XmlSerialName. @XmlValuemakes a property the element's text content.- A list of classes becomes repeated elements with no wrapper. A list of primitives needs
@XmlChildrenNameto name each item.
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 & 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 & Jerry <Classic></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=[])])
XML.v1 { }creates a configured instance with the recommended 1.0 defaults. Create it once and reuse it.- Without
xmlVersion = XmlVersion.XML10, the declaration saysversion='1.1'. Some older parsers reject XML 1.1.XmlDeclMode.Noneleaves out the declaration. - Nulls are skipped when writing.
@EncodeDefault(NEVER)also skips the empty<tags/>element. - Elements can come in any order when decoding:
<year>before<title>worked. - Without
@XmlSerialName, an element is named after the simple class name (<Book>), so you need it whenever the XML uses lowercase names.
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"
- Attributes without a prefix are not in any namespace, which is why
id,qtyandstatushave nos:. - The
@XmlElement(false)onstateis needed. Without it, xmlutil writes the enum as an element named after the enum type (<s:Status>PAID</s:Status>). Check the output of new mappings before relying on the defaults. - Unknown attributes and elements throw
UnknownXmlFieldExceptionwith the line and column. That catches typos, but feeds and third-party APIs add fields over time. For those, usepolicy { ignoreUnknownChildren() }.
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 & 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 & Jerry <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
- Lists are wrapped by default: a
booksproperty becomes<books><books>...</books></books>.@JacksonXmlElementWrapper(useWrapping = false)writes the items directly. You can turn off wrapping for all lists with.defaultUseWrapper(false)on the builder. - The root element name comes from
@JsonRootName. Without it Jackson uses the simple class name (<Library>). In Jackson 3,@JacksonXmlRootElementis deprecated. >in text isn't escaped. That is valid XML. Only<and&must be escaped in text.- In the untyped tree every value is a string (
"year":"2008"), because XML has no number type. Attributes and elements look the same. XmlMapperis thread-safe and expensive to build. Keep one instance.- Jackson parses with Woodstox and doesn't process DTDs by default. A document that uses an entity declared in its
DOCTYPEfails withUndeclared general entity "x", so the XXE attack from earlier doesn't work.
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("<")
'>' -> append(">")
'&' -> append("&")
'"' -> append(""")
'\'' -> append("'")
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 & Jerry's "<Cookie Dough>""/>
true
{"item":"a"}
{"item":["a","b"]}
#text
'
x
'
- String templates. Building XML with
"<tag>$value</tag>"breaks as soon as a value contains&,<or a quote. It is also an injection hole: a user name like</name><admin>true</admin>adds elements. Use DOM, StAX, a serializer, or at least an escape function like the one above. - One vs. many. In untyped trees (Jackson's
readTree(), or XML-to-JSON converters), a single child becomes an object and repeated children become an array. Code that expects a list breaks when a feed happens to have one entry. Typed classes withList<T>properties don't have this problem. - Whitespace text nodes. The indentation between elements is text.
firstChildis often a#textnode, not the first element. Use thechildren()helpers from the DOM section, or XPath. - Encoding. Read XML as bytes (
InputStream,File,Path) and let the parser find the encoding from the declaration. If you read a file into aStringwith the wrong charset first, non-ASCII characters are corrupted before parsing starts. See Unicode and encodings. - Invalid characters. XML 1.0 forbids most control characters (
\u0000to\u001Fexcept tab, newline and carriage return), even when escaped. Strip them from user data before writing.
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.