CodeGym /Courses /Kotlin SELF /DOM parsing: Document, Element, attributes, and textConte...

DOM parsing: Document, Element, attributes, and textContent

Kotlin SELF
Level 50, Lesson 1
Available

1. Introduction

If you’ve ever seen code that “parses XML” using substringBefore("</tag>"), then you know two facts: sometimes that code even works… and that is exactly why it’s especially dangerous. DOM parsing is the path where XML becomes a tree of objects in memory. We stop catching corners with strings and start “walking the structure” like folders in a file explorer.

DOM is convenient when the document is not gigantic and we need to freely extract different pieces of data. Yes, DOM loads the entire XML into memory (that’s the price of convenience), but after that we can grab the root element, inspect attributes, find all <expense> tags, read the text inside <amount>, and so on.

And a nice bonus: Kotlin on the JVM can easily call Java APIs, and a DOM parser is a classic Java tool. So we’ll use ready-made, time-tested libraries without reinventing the wheel out of split() and hope. Kotlin is positioned as a language that is interoperable with Java, so “calling the Java DOM API from Kotlin” is a normal real-world scenario.

Mini DOM-parsing pipeline

Before we dive into the details, let’s assemble the big picture of the process. In the DOM approach there are usually two stages: first we parse XML into a Document, and then we extract data from that tree.

Here’s a simple flowchart (yes, programmers draw arrows so they cry less during debugging later):

flowchart TD
    A[XML as String / file] --> B["DocumentBuilder.parse(...)"]
    B --> C[Document]
    C --> D[documentElement: Element]
    D --> E[Find elements / read attributes / textContent]
    E --> F[Your Kotlin objects / strings / numbers]

In this lecture we’re interested in everything up to and including block E: how to correctly obtain a Document, how to safely get an Element, and how to read attributes and text.

2. The DOM model: Document, Element, NodeList

Before writing code, it helps to get the terminology straight. DOM is the “Document Object Model”— a document model as a tree. The top of the tree is the document itself, below are elements (tags), and inside elements are other elements and text.

So your brain doesn’t try to memorize everything at once, here’s a simple mapping: XML → tree → nodes.

Below is a small correspondence table so you don’t get confused about what is an “XML concept” and what is a “DOM class”:

In XML In DOM (JVM) What it means in code
The whole document
org.w3c.dom.Document
A “box” that contains the whole tree
Tag <user>...</user>
org.w3c.dom.Element
An element node: it has a tag name, attributes, and content
Attribute id="42"
Element.getAttribute("id")
Get the attribute’s string value
A set of same-type tags <item>...</item>
org.w3c.dom.NodeList
A DOM-world collection: length + indexed access
Text inside a tag
Element.textContent
All text inside the element (often with spaces/newlines)

And now an important “gotcha” for beginners: NodeList is not a List. It doesn’t have map, forEach, indices, or other joys of Kotlin collections. In the DOM world you often have to live “the old way”: 0 until nodes.length and nodes.item(i).

3. Getting a Document from XML

XML string → Document

To obtain a Document, we need a DOM parser. In Java/JVM it’s created through the DocumentBuilderFactory factory, which produces a DocumentBuilder. And the DocumentBuilder already knows how to parse(...).

Let’s start with the minimal example: the XML is right in a Kotlin string.


import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val xml = """<user id="42"><name>Ann</name></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    println(doc.documentElement.tagName) // user
}

Notice the byteInputStream(). The parser usually works with byte streams (InputStream), and a string is just convenience for us. We turn the string into a byte stream and feed it to the parser.

There’s an important practical idea here: XML is text, but the parser reads bytes. In real projects you’ll think a lot about encodings, but within this lecture it’s enough to understand a simple rule: “the parser takes an InputStream, not ‘just a string’”.

Root element: documentElement

When the Document is already obtained, you want to understand: “what’s inside?” The starting point is almost always the same: the root element.

doc.documentElement returns an Element. That’s the root of the tree (that very “top tag” that wraps everything else).

import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val xml = """<user id="42"><name>Ann</name></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val root = doc.documentElement
    println(root.tagName) // user
}

Why does this matter? Because later you’ll often read “contextually”: first you confirm that the root is <expenses>, and only then you look for <expense> inside it. This approach makes code more predictable (and slightly less magical—magic you end up feeding yourself).

XML from a file: parse(File)

When XML arrives not as a string but as a file (the classic “export a report” case), you may want to read it directly. A DOM parser can parse a file without an intermediate readText(), meaning you don’t have to read the file into a string first.

Mini example “file → Document”:

import java.io.File
import javax.xml.parsers.DocumentBuilderFactory

fun parseXmlFile(path: String) =
    DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(File(path))

Usage:

import org.w3c.dom.Element

fun main() {
    val doc = parseXmlFile("expenses.xml")
    val root = doc.documentElement

    println(root.tagName) // expenses
    val first = root.getElementsByTagName("expense").item(0) as? Element
    println(first?.getAttribute("id")) // for example: e1
}

Why can this be more convenient? Because parse(File) opens the stream and reads the data itself. And if you do File(path).readText() and then parse(...), you first create a large string in memory and then convert it back to bytes. For small files it’s not a tragedy, but the habit of “not copying large data unnecessarily” is usually a good one.

Parsing errors and try/catch

A DOM parser is pretty strict: if the XML is not well-formed, it will throw an exception. And that’s normal: it’s not required to guess what exactly you meant when you forgot to close a tag. (Although it would be cool if it also brought tea and nodded sympathetically.)

Wrapping parsing in try/catch is good practice, especially in CLI apps where you want to keep running instead of crashing.

import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val brokenXml = "<user><name>Ann</user>" // name is not closed

    try {
        DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(brokenXml.byteInputStream())

        println("Parsed OK")
    } catch (e: Exception) {
        println("XML parse failed: ${e.message}")
    }
}

Here we catch Exception as broadly as possible (for a learning example that’s fine). In production code you often catch more specific types, but for now it’s more important to understand the idea: “parsing is a potentially crashing operation”.

4. Reading data from DOM: attributes, elements, text

Attributes: getAttribute(...)

Attributes in XML look like id="42". In DOM they are read like this:

import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val xml = """<user id="42"></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val id = doc.documentElement.getAttribute("id")
    println(id) // 42
}

And here the “fun” begins: if the attribute is missing, many people expect null. But getAttribute(...) usually returns an empty string.

import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val xml = """<user></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val id = doc.documentElement.getAttribute("id")
    println("id='$id'") // id=''
}

This means that “the attribute exists but is empty” and “the attribute does not exist” look the same to you—both cases produce "". That’s why in real code you almost always add an extra check:

val id = root.getAttribute("id").trim()
val idOrNull = id.takeIf { it.isNotEmpty() }

We use trim() because sometimes an attribute can contain spaces (and you don’t want to happily accept " " as a meaningful value).

Finding elements: getElementsByTagName(...)

When we have the root, the next typical step is to find nested elements. The simplest way: getElementsByTagName("name"). It returns a NodeList.

Let’s do a mini example:

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

fun main() {
    val xml = """<user><name>Ann</name></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val nodes = doc.getElementsByTagName("name")
    println(nodes.length) // 1

    val nameEl = nodes.item(0) as Element
    println(nameEl.tagName) // name
}

There are several nuances here:

First, nodes.length is the number of elements. If length == 0, then item(0) returns null, and casting with as Element will crash the program. So the rule is simple: check first, access second.

Second, getElementsByTagName searches across the entire subtree, not only among direct children. That is, if you have <user><profile><name>...</name></profile></user>, then user.getElementsByTagName("name") will find <name> inside <profile>. Sometimes that’s convenient, sometimes it’s surprising. At this stage it’s enough to remember: the search is “deep”.

To avoid crashing on an empty result, you can use a safe cast as? and a null check:

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

fun main() {
    val xml = """<user></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val nameEl = doc.getElementsByTagName("name").item(0) as? Element
    println(nameEl?.tagName) // null
}

Text inside a tag: textContent

Now we get to the “tastiest” part: how to retrieve the value inside <name>Ann</name>.

In DOM this is done via textContent:

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

fun main() {
    val xml = """<user><name>Ann</name></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val nameEl = doc.getElementsByTagName("name").item(0) as Element
    println(nameEl.textContent) // Ann
}

And now a real-life example: XML is often nicely formatted with newlines and indentation. For a human that’s great; for a parser it’s still text.

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

fun main() {
    val xml = """
        <user>
            <name>
                Ann
            </name>
        </user>
    """.trimIndent()

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val nameEl = doc.getElementsByTagName("name").item(0) as Element
    println(nameEl.textContent)          // "\n                Ann\n            "
    println(nameEl.textContent.trim())   // Ann
}

That’s why trim() next to textContent is not “just in case”—it’s almost standard hygiene.

One more nuance: textContent returns all text inside an element, including text from nested elements. For example:

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

fun main() {
    val xml = """<msg>Hello <b>World</b>!</msg>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val msgEl = doc.documentElement
    println(msgEl.textContent.trim()) // Hello World!
}

That’s fine; it’s just important to understand: textContent is “everything textual inside”, not “only the direct text child”.

A bit of DOM hygiene so your code stays calm

When you start writing DOM code, a typical temptation appears: to do item(0) as Element everywhere and believe the world is kind. The world is not kind. It just hasn’t shown you the XML where <amount> was omitted, or written as <Amount> (a different case-sensitive universe).

So a good style is to extract small helper functions that hide checks, trim(), and safe casts. We’ll do that in the next section— there you’ll see firstTagText, and the main parsing code will become noticeably more readable, with checks collected in one place.

Another useful technique is to normalize strings right when reading: trim(), sometimes lowercase() for categories (if your format allows it), emptiness checks. DOM parsing almost always goes together with “data preparation”, otherwise you’ll get category = " food " and then wonder why grouping doesn’t work.

5. Example: importing expenses from XML into a list

So the examples don’t live a separate “vacuum life”, let’s embed DOM reading into logic we already know: we have a console expense-tracking app, and suddenly accounting (or the bank) provides an export… in XML. Because “that’s how it historically happened”. Don’t ask—this is like “why the office printer only works if you ask it nicely”.

Let the XML look like this:

<expenses>
  <expense id="e1">
    <amount>120.50</amount>
    <category>food</category>
    <comment>Lunch</comment>
  </expense>
</expenses>

For simplicity, let’s define an expense model (if your project already has one—use it; what matters here is not the model, but DOM extraction):

data class Expense(
    val id: String,
    val amount: Double,
    val category: String,
    val comment: String
)

Now let’s write a small helper: “get the text of the first tag inside parent”. Note: we return String? because the element may be missing.

import org.w3c.dom.Element

fun firstTagText(parent: Element, tag: String): String? {
    val node = parent.getElementsByTagName(tag).item(0) as? Element ?: return null
    return node.textContent.trim()
}

And now the main function: parse XML and get a list of Expense.

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

fun parseExpenses(xml: String): List<Expense> {
    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val nodes = doc.getElementsByTagName("expense")
    val result = mutableListOf<Expense>()

    for (i in 0 until nodes.length) {
        val expenseEl = nodes.item(i) as? Element ?: continue

        val id = expenseEl.getAttribute("id").trim()
        val amount = firstTagText(expenseEl, "amount")?.toDoubleOrNull()
        val category = firstTagText(expenseEl, "category")
        val comment = firstTagText(expenseEl, "comment") ?: ""

        if (id.isNotEmpty() && amount != null && category != null) {
            result.add(Expense(id, amount, category, comment))
        }
    }

    return result
}

Here we intentionally use the most “down-to-earth” techniques: toDoubleOrNull(), null checks, trim(). We’re not building a fancy error system yet—we want to learn how to read DOM carefully without crashing, because input data is almost always “sometimes fine, sometimes… well, you know”.

Let’s test with a small input:

fun main() {
    val xml = """
        <expenses>
            <expense id="e1">
                <amount>120.50</amount>
                <category>food</category>
                <comment>Lunch</comment>
            </expense>
            <expense id="e2">
                <amount>999</amount>
                <category>tech</category>
                <comment>Keyboard</comment>
            </expense>
        </expenses>
    """.trimIndent()

    val items = parseExpenses(xml)
    println(items.size)        // 2
    println(items.first().id)  // e1
}

6. Common mistakes in DOM parsing

Mistake #1: calling item(0) without checking length.
This is the most common cause of unexpected crashes. An element may be missing in XML: an old format version, a different vendor, or just human error. If you do nodes.item(0) as Element, then with an empty NodeList item(0) returns null, and then either the cast crashes or you get an NPE a bit later. The cure is the habit: “check first, access second”, or using as? and an early return.

Mistake #2: expecting null from getAttribute(...).
Beginners often write val id = el.getAttribute("id") ?: ..., and then wonder why ?: doesn’t trigger. getAttribute usually returns an empty string, and that’s a separate logic branch. As a result, without trim() and isNotEmpty() you may “accept” a missing attribute as “well, it seems like there is a value”.

Mistake #3: forgetting trim() on textContent and getting “invisible” spaces.
XML formatting (indentation, line breaks) is also text. Therefore textContent may contain "\n 120.50\n" instead of "120.50". If you then do toDouble() (or string comparisons), you’ll get errors where everything “looks fine”. In tutorials it looks like a small detail; in real projects it turns into hours of debugging: “why won’t the number parse, it’s a number”.

Mistake #4: thinking getElementsByTagName searches only among direct children.
This method searches across the entire subtree, and sometimes that leads to unexpected results: you wanted to find <amount> specifically inside a particular <expense>, but instead you found all <amount> from nested blocks (or from elsewhere if the structure is more complex). In small documents it’s not noticeable, and then suddenly “the first <amount>” is not the one you meant. At this stage, discipline helps: search from the needed element (context) and keep the XML structure as clear as possible.

1
Task
Kotlin SELF, level 50, lesson 1
Locked
User passport
User passport
1
Task
Kotlin SELF, level 50, lesson 1
Locked
Missing id
Missing id
1
Task
Kotlin SELF, level 50, lesson 1
Locked
Book title
Book title
1
Task
Kotlin SELF, level 50, lesson 1
Locked
Product showcase
Product showcase
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION