Working with XML in Kotlin: Libraries, Parsing, and Document Creation
XML (eXtensible Markup Language) remains a popular format for storing and transmitting structured data, especially in legacy systems, configuration files, and web services. Kotlin, being fully compatible with Java, provides access to all classic Java libraries for working with XML, as well as having native solutions. In this article, we will cover the main approaches: parsing, creating, and serializing XML documents in Kotlin.
1. Built-in JDK Tools: DOM, SAX, StAX
Thanks to full interoperability with Java, you can directly use standard APIs in Kotlin:
- DOM (Document Object Model) — loads the entire document into memory, convenient for modifications.
- SAX (Simple API for XML) — an event-driven parser with minimal memory consumption.
- StAX (Streaming API for XML) — a streaming parser with a cursor or event-based approach.
Example of parsing XML using DOM in Kotlin:
import javax.xml.parsers.DocumentBuilderFactoryimport org.w3c.dom.Element
fun parseXmlWithDom(xmlString: String) { val factory = DocumentBuilderFactory.newInstance() val builder = factory.newDocumentBuilder() val document = builder.parse(xmlString.byteInputStream()) val root = document.documentElement
val items = root.getElementsByTagName("item") for (i in 0 until items.length) { val item = items.item(i) as Element val name = item.getElementsByTagName("name").item(0).textContent val price = item.getElementsByTagName("price").item(0).textContent println("Item: $name, Price: $price") }}2. Simple XML Library (org.simpleframework.xml)
Simple XML is a popular library for serializing/deserializing objects to/from XML. It uses annotations and does not require configuration files. It is well-suited for REST APIs with XML responses.
Dependency (Gradle):
implementation("org.simpleframework:simple-xml:2.7.1")Example model and deserialization:
import org.simpleframework.xml.*import org.simpleframework.xml.core.Persister
@Root(name = "catalog")data class Catalog( @field:ElementList(inline = true) var books: List<Book> = emptyList())
@Root(name = "book")data class Book( @field:Element(name = "title") var title: String = "", @field:Element(name = "author") var author: String = "", @field:Attribute(name = "id") var id: Int = 0)
fun deserializeXml(xml: String): Catalog { val serializer = Persister() return serializer.read(Catalog::class.java, xml)}3. kotlinx.serialization with XML Format
For multiplatform projects (KMP), it is convenient to use kotlinx.serialization with a custom XML format. There are third-party adapters, such as kotlinx-serialization-xml (from the community).
Example with the nl.adaptivity.xmlutil library (supports JVM, JS, Native):
import nl.adaptivity.xmlutil.serialization.XMLimport kotlinx.serialization.*
@Serializabledata class Person( val name: String, @XmlSerialName("age") val years: Int)
fun main() { val xml = XML { indent = 4 xmlDeclMode = XmlDeclMode.Auto } val person = Person("Alice", 30) val result = xml.encodeToString(Person.serializer(), person) println(result) // <Person> // <name>Alice</name> // <age>30</age> // </Person>}4. XPath and XSLT in Kotlin
For data selection based on complex criteria, use XPath. In Kotlin, this is done through the standard Java classes javax.xml.xpath