Kotlin XML XSLT using libxml2 and libxslt

Submitted by Dickens A S on Sun, 05/07/2023 - 08:33

This Article demonstrates how to parse xml in Kotlin Native using libxml2 and libxslt 

If the devloper working in linux, then the developer can install libxml and libxslt 

For example in Ubuntu Focal

sudo apt-get -y install libxml2 libxml2-dev libxml2-utils
sudo apt-get -y install libxslt1-dev libxslt1.1

if the developer user windows, then the developer can install MSYS2 and install the libraries

pacman -S mingw-w64-x86_64-libxslt
pacman -S mingw-w64-x86_64-libxml2

Once this is installed the developer can use the below Kotlin native DEF files to organize the compiler


headers = libxml/parser.h libxml/tree.h
package = libxml2
libraryPaths = C:/msys64/mingw64/lib
linkerOpts =  -LC:/msys64/mingw64/lib -L/usr/lib/x86_64-linux-gnu -lxml2
compilerOpts = -LC:/msys64/mingw64/lib -L/usr/lib/x86_64-linux-gnu -lxml2


headers = libxslt/xslt.h libxslt/xsltutils.h libxslt/transform.h
package = libxslt
libraryPaths = C:/msys64/mingw64/lib
linkerOpts =  -LC:/msys64/mingw64/lib -L/usr/lib/x86_64-linux-gnu -lxslt
compilerOpts = -LC:/msys64/mingw64/lib -L/usr/lib/x86_64-linux-gnu -lxslt

This will enable the kotlin native importable library

Then the developer can do kotlin native source code below

package plot

import kotlin.native.concurrent.*
import platform.posix.sleep
import kotlinx.cinterop.*
import kotlin.text.*
import libxslt.*

fun main() {
    var xml = 
	      <book>Book 1</book>
	      <book>Book 2</book>
	var xmlDoc = xmlReadDoc(xml, null, null, 0)
    var xsl = 
          <xsl:template match='books'>
            <xsl:for-each select='//book[2]'>
              <xsl:sort lang='en'/>
              <xsl:copy-of select='.'/>
    var xslDoc = xmlReadDoc(xsl, null, null, 0)
    var style = xsltParseStylesheetDoc(xslDoc)
    if (style == null)
    var tctxt = xsltNewTransformContext(style, xmlDoc)
    var resultDoc = xsltApplyStylesheetUser(style, xmlDoc, null, null, null, tctxt)
    xsltSaveResultToFile(stdout, resultDoc, style)


<?xml version="1.0"?>
<book>Book 2</book>

This output is based on XPath //book[2]

Thats All :)

Add new comment