This tutorial shows you multiple examples

  • Parse(read) xml file in Kotlin
  • Write to Xml File in Kotlin

How to read XML files in Kotlin

Let’s declare a users.xml file for reading example

<users>
  <user id="1" >
    <id>1</id>
    <name>john</name>
    <!-- name of employee -->
    <salary>5000</salary>
    <!-- salary of employee -->
  </user>
  <user id="2" >
    <id>2</id>
    <name>Eric</name>
    <salary>3000</salary>
  </user>
  <user id="3">
    <id>3</id>
    <name>Mark</name>
    <salary>5100</salary>
  </user>
</users>

XML contains

  • users is a root element
  • Contains multiple user tags with the attribute of id
  • Each User object contains id, name, and salary tags

Let’s discuss an example of reading XML files in Kotlin.

javax.xml.parsers is a package used for reading XML files in Kotlin.

import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import org.w3c.dom.Document

fun main() {
  // Input XML file
  val file = "users.xml"

  // Read the XML file into an Kotlin document
  val document = parseXML(filePath)

  // Access elements and attributes
  document.documentElement.normalize()
  val root = document.documentElement
  println("${root.nodeName}")

  val nodeList = root.childNodes
  for (i in 0 until nodeList.length) {
    val node = nodeList.item(i)

    if (node.nodeType == Document.ELEMENT_NODE) {
      val element = node as org.w3c.dom.Element
      println("Tag: ${element.tagName}")

      // Access attributes
      val attributes = element.attributes
      for (j in 0 until attributes.length) {
        val attribute = attributes.item(j)
        println("Attribute Node: ${attribute.nodeName} = ${attribute.nodeValue}")
      }

      // Access text content
      println("Content : ${element.textContent}")
    }
  }
}

fun parseXml(path: String): Document {
  // Create a builder class
  val documentBuilderFactory = DocumentBuilderFactory.newInstance()
  val docBuilder = documentBuilderFactory.newDocumentBuilder()
  return docBuilder.parse(File(path))
}

In this example

  • First, Create DocumentBuilder using DocumentBuilderFactory class.
  • Parse the xml file using parse(File(path) , It reads XML file content and reads into a Document.
  • document.documentElement.normalize() checks and makes the XML object is valid
  • document represents an XML FIle content structure, It has the following methods or properties
    • documentElement: Returns root element or a node of a XML content
    • childNodes: Returns the child nodes under a Root node, It is a List of nodes
    • getElementsByTagName: Return node with a tag name,
    • getAttributes: Attributes for a given node, in this case id=1
    • getTextContent: return text content.
  • the above example iterates child nodes, printed tag names, attributes, and text content to the console.

Write to XML file in Kotlin

javax.xml.transform package is used to create an XML Document Structure in Kotlin.

import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.File

fun main() {
    // Create a new XML document
    val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance()
    val builder = factory.newDocumentBuilder()
    val document = builder.newDocument()


    // Add nodes, attributes, content
    val rootElement = document.createElement("users")
    document.appendChild(rootElement)

    val user1 = document.createElement("user1")
    user1.setAttribute("id", "1")
    user1.textContent = "john"
    rootElement.appendChild(user1)

    val user2 = document.createElement("user2")
    user2.setAttribute("id", "2")
    user2.textContent = "Eric"
    rootElement.appendChild(user2)

    // Save the document to an XML file
    val transformerFactory = TransformerFactory.newInstance()
    val transformer = transformerFactory.newTransformer()
    val source = DOMSource(document)
    val result = StreamResult(File("result.xml"))

    transformer.transform(source, result)
    println("XML file Created .")

}
  • First, Create a new Document using the below steps

    • Create a class using a Factory class javax.xml.parsers.DocumentBuilderFactory.newInstance()
    • Create a DocumentBuilder on this factory and call newDocument to create a Document.
  • Once the Document is created, create a Document structure using the following methods

    • document.createElement(") used to create a node with a tag name, Calling the CreateElement method Creates a Root node for the first time, else creates a child node. Once create a node, You can use the below classes for setting content, child, and attributes.
  • textContent: adding text content to a node

  • appendChild: Addes the newly created node to the existing node.

  • setAttribute("id", "1"): set the attributes( key and value pairs) for a node.

  • Once the Document structure is ready, You need to write a code to write doc to XML file.

  • `Following are steps.

  • TransformerFactory.newInstance() create a Factory class. Next, Create a transform and call the trasforme method.