Software Development

How to read XML in Kotlin using DOM Parser

This post demonstrates how to read XML files using DOM Parser which parses and loads the entire XML into memory in a Tree structure which makes it very easy to traverse and manipulate elements.

We are using Kotlin 1.1.

Reading XML files

When reading an XML file using a DOM parser, we create a org.w3c.dom.Document object which represents the XML file whose contents are stored as a tree of elements (technically known as nodes).

XML File – Input File

This is our XML file that’ll be parsed and load into memory by a DOM parser. It’s a copy of books.xml from Microsoft MSDN.

Kotlin Codes – Iterative Traversal

There are no classes here. It is just a Kotlin script with a main function.

Output:

Kotlin Codes – Recursive Traversal

Notice that we created a DomRecursiveTraverse class that has a method that traverses a DOM object from a Node object starting point.

Output:

References

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like