1. Why do we need XML if we have JSON?
XML is a thing many people first see as “scary angle brackets,” and then suddenly run into it in real integrations: bank exports, enterprise buses, configs, old (and not so old) protocols. Our goal today is to learn to read XML with a developer’s eyes: understand what is data, what is structure, and why sometimes “but it looks nicely written” turns into a parser error.
If you’re thinking “JSON is simpler, why these 2007-style angle brackets,” that’s totally normal. But reality likes to bring us not only fresh tech, but also the kind that “has been set up, works for 15 years, don’t touch it.” XML is like that server in the closet: it may look intimidating, but it does important work and sometimes it doesn’t even make noise.
XML is often chosen when strict structure is needed, compatibility with legacy systems matters, or historically there are many tools around it: schemas, transformations, complex queries. At the same time, XML is still plain text—you can store it in a file, send it over the network, log it, diff it (carefully), and yes, accidentally break it with one extra character.
It’s important to separate two questions right away. First: “Can XML be parsed?”—that’s about format correctness (well‑formed). Second: “Does XML contain the right data for our task?”—that’s about business validation. Today we focus on the first: learning to read XML as a format and understand why it might not parse at all.
2. Basic XML structure
Element and tree
When you look at XML, it helps to switch your brain into “I see a tree” mode. Not a line, not text, not a set of characters, but a hierarchy: we have a root, the root has children, children have their own children, and so on. In this sense, XML is very similar to JSON: that’s also a tree. It’s just that in XML the tree is written using tags.
The smallest “building block” of XML is an element. An element has a name (the tag name), may have attributes, and has content (text and/or nested elements). The element itself is written as a pair of tags: opening and closing.
Here’s the most minimal XML example (one root element, with text inside):
fun main() {
val xml = "<message>Hello</message>"
println(xml) // <message>Hello</message>
}
Visually, it looks like a “wrapper around text.” But if you think in terms of a tree, it’s:
- root: message
- text inside: Hello
For multi-line XML, it’s convenient to use """...""" and then trimIndent() so that indentation looks nice both in code and in the result:
fun main() {
val xml = """
<message>
Hello
</message>
""".trimIndent()
println(xml)
// <message>
// Hello
// </message>
}
Pay attention: line breaks and spaces become part of the text. We’ll discuss later in detail why this matters (and why sometimes you suddenly have to write trim()).
Nesting and a single root
When XML gets a bit more complex, nesting appears. This is literally “one element inside another.” And here rules start to resemble properly placed parentheses in math: open—close, and close in the correct order. Computers are very pedantic: they won’t accept “almost correct.” There is no “I get what you meant” mode.
Example: a user with an id and a name inside:
fun main() {
val xml = """
<user id="42">
<name>Ann</name>
</user>
""".trimIndent()
println(xml)
}
If you represent this as a tree, you get:
flowchart TD
U["user (id=42)"]
N["name"]
T["text: Ann"]
U --> N --> T
Here user is the root element (root). And name is a nested element (child).
XML has a strict rule: a document must have exactly one root element. Not two “siblings,” not “but I have two data blocks.” If you want two blocks, you must wrap them in a single common root.
Here’s an example that looks “logical” but is considered an invalid XML document:
fun main() {
val broken = """
<a>1</a>
<b>2</b>
""".trimIndent()
println(broken)
// This is NOT a single XML document: two root elements
}
And here it’s fine (there is one root root):
fun main() {
val ok = """
<root>
<a>1</a>
<b>2</b>
</root>
""".trimIndent()
println(ok)
}
3. Attributes and empty elements
When you start working with XML, attributes are the first thing that seems “obvious,” and then they troll beginners a little. An attribute is a key="value" pair inside the opening tag. In the example above, id="42" is an attribute of the user element.
The typical meaning of attributes is “small properties of an element.” For example, an identifier, a code, a flag, a type. But it’s important to remember: an attribute value in XML is a string. Even if it says 42, the parser sees it as "42". In Kotlin, you’ll decide yourself later: keep it as a string or convert it to a number (toIntOrNull()), like we did before.
Example with two attributes:
fun main() {
val xml = """<file name="report.xml" size="128" />"""
println(xml) // <file name="report.xml" size="128" />
}
Here we meet another element form: an empty element (self‑closing tag)—<file ... />. This is just a shortened notation for when there’s nothing inside the element. That is, these two notations are equivalent in meaning:
fun main() {
val a = "<file name=\\"report.xml\\" />"
val b = "<file name=\\"report.xml\\"></file>"
println(a) // <file name="report.xml" />
println(b) // <file name="report.xml"></file>
}
Notice the escaping of quotes \" in a Kotlin string. In real code, you’ll more often use triple quotes so you don’t have to escape:
fun main() {
val xml = """<file name="report.xml" />"""
println(xml) // <file name="report.xml" />
}
4. Text and whitespace as data
When we format XML with nice indentation, it seems like spaces are “just for humans.” But the parser sees it differently: spaces and line breaks are text nodes (we’ll talk about nodes in detail in the next lecture, but it’s important to feel the idea already). So if you wrote:
<name>
Ann
</name>
then inside name there is text that looks roughly like "\n Ann\n" (newline, spaces, Ann, newline). In reality, it depends a bit on the specific parser, but the general idea is: formatting becomes part of the text.
Practically, this means a simple thing: when you extract text from XML, you almost always do .trim(). So the habit “normalize the string after reading” (which we practiced with input and JSON) shows up all the time in XML.
A mini example in Kotlin to see “invisible” characters: we just print the string and its length.
fun main() {
val text = """
Ann
""".trimIndent()
println(text) // Ann
println(text.length) // 3
}
And now a similar idea, but with “internal” newlines:
fun main() {
val xml = """
<name>
Ann
</name>
""".trimIndent()
println(xml)
println("XML length = ${'$'}{xml.length}") // XML length = ...
}
We aren’t parsing XML yet, but we already understand: formatting affects bytes/characters. This is not “philosophy”—it’s the reason for half of weird bugs like “why does the name have a leading space?”
5. Well‑formed XML rules
The term well‑formed (literally “properly formed”) means: the XML follows the basic grammar and can be parsed as an XML document. This is not about “the data is correct,” but about “this is XML at all, not a set of characters pretending to be XML.”
You can think of well‑formed rules as rules for parentheses and quotes: if you break them—that’s it, the parser stops. For practice, it’s convenient to keep them as a small table.
| Rule | What it means in plain terms | Error example |
|---|---|---|
| One root element | You can’t have two “top-level” elements next to each other | |
| Every opened tag must be closed | If you opened <x>, close it with </x> | |
| Nesting must be correct | Close in reverse order (like parentheses) | |
| Tag names are case-sensitive | <Name> and </name> are different names | |
| Attributes must be quoted | You can’t do id=42; you must do id="42" | |
| Special characters in text must be escaped | & and < can’t be written “as-is” | |
Let’s look at a couple of typical “broken” examples so your brain starts recognizing them at first glance.
Incorrect nesting:
fun main() {
val broken = "<a><b></a></b>"
println(broken) // <a><b></a></b>
// The parser will say: "I don't understand what you're closing"
}
Unclosed tag:
fun main() {
val broken = "<user><name>Ann</user>"
println(broken) // <user><name>Ann</user>
// <name> is not closed; the document is invalid
}
Attribute without quotes:
fun main() {
val broken = "<user id=42></user>"
println(broken) // <user id=42></user>
// For XML this is an error: id must be in quotes
}
6. Escaping and entities
Now comes the part that breaks beginners most often. In XML there are several characters that have special meaning. The most important are & and <. If you put them in text “as-is,” XML can become unparseable because the parser will think you’re starting an entity (&...;) or a new tag (<tag>).
That’s why XML uses entities—special sequences that mean “insert the character, but safely.” The basic entities are:
| Character | How to write in XML | Where it appears |
|---|---|---|
|
|
in text, in attributes |
|
|
in text, in attributes |
|
|
usually allowed in text, but often escaped for symmetry |
|
|
especially important inside attr="..." |
|
|
when attributes are written with single quotes |
Example of “bad” XML:
fun main() {
val unsafe = "<title>Tom & Jerry</title>"
println(unsafe) // <title>Tom & Jerry</title>
// In XML this is NOT ok: & must be escaped
}
Correct version:
fun main() {
val safe = "<title>Tom & Jerry</title>"
println(safe) // <title>Tom & Jerry</title>
}
Mini utility: escaping text for XML
Writing XML by hand is an activity where it’s easy to commit a “symbolic crime” (accidentally insert &). So even in a learning app, it’s useful to have a small function that escapes text. It doesn’t have to be perfect for every case in the world, but it should be understandable.
The order matters: replace & first, and only then < and the rest. Otherwise you risk “double-escaping” the already inserted &.
fun escapeXmlText(text: String): String {
return text
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
}
This idea pairs well with our approach “normalize and validate input data.” And yes, string templates in Kotlin make string assembly much nicer, so next we’ll build XML using templates, and we’ll run text through escapeXmlText.
7. Practical example: exporting a report to an XML string
We continue developing our console data analyzer app (in the previous lecture it accepted JSON and built reports). Today we are not parsing XML, but we’ll add the ability to produce an XML export, because it’s a great way to reinforce: elements, attributes, text, escaping, and well‑formed.
Let’s imagine that inside the app we have a report result:
- report name
- record count
- a short comment (which may contain special characters)
Let’s make a function that creates XML:
fun buildReportXml(title: String, count: Int, note: String): String {
val safeTitle = escapeXmlText(title)
val safeNote = escapeXmlText(note)
return """
<report title="$safeTitle" count="$count">
<note>$safeNote</note>
</report>
""".trimIndent()
}
There are several “good” habits here at once. We use a multi-line string and trimIndent() so the XML is readable in code and in the output. We explicitly escape text so we don’t break the document with an & character. And we remember that count in an attribute still becomes a string.
Now an example usage in main:
fun main() {
val xml = buildReportXml(
title = "Sales & Marketing",
count = 3,
note = "Top < 10 entries, ok"
)
println(xml)
// <report title="Sales & Marketing" count="3">
// <note>Top < 10 entries, ok</note>
// </report>
}
We got well‑formed XML that won’t fall apart because of & and <. And even if you can’t parse XML yet, you can already produce a correct document and visually verify what’s going on.
8. Common mistakes when working with XML as a format
Mistake #1: confusing “looks nice” with “well‑formed.”
A beginner looks at XML, sees indentation, line breaks, neat tags—and thinks that if it’s pretty, it must be correct. But XML is not about beauty; it’s about strict grammar: one incorrectly closed tag or two roots in a row, and the parser will refuse to work. “Almost correct” in XML means “incorrect.”
Mistake #2: inserting text into XML without escaping.
This is a classic: you substituted a string with & or < into <title>...</title>, and the document suddenly stopped being XML. The most annoying part is that visually it looks “normal.” That’s why even in learning examples it’s useful to discipline yourself: run any user text through escapeXmlText, otherwise you’ll catch errors in the most unexpected places.
Mistake #3: expecting that spaces and line breaks “don’t count.”
In XML, formatting is also text. If you write <name>\n Ann\n</name>, inside there will be text with spaces and newlines. Then you wonder why string comparison doesn’t match or why extra spaces show up in the output. In real XML processing there’s almost always a text normalization step: at least trim().
Mistake #4: thinking attributes are “almost numbers/booleans.”
Attributes in XML are always strings. Even if you wrote count="3", it’s the string "3". So any “typing” (to Int, Boolean, enum) happens on your side. In that sense, XML is similar to input via readln(): first a string, then an attempt to parse, then error handling.
Mistake #5: breaking the document with incorrect nesting.
<a><b></a></b> is an example that often appears during manual string assembly or careless copy/paste. Think of tags like parentheses: close strictly in reverse order. If you catch yourself thinking “it’s hard to follow visually,” it’s time either to simplify the structure, or to stop building XML by hand and switch to a proper parser/generator (but that’s the next step in the course).
GO TO FULL VERSION