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
libxml2.def
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
libxslt.def
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 =
"""
<books>
<book>Book 1</book>
<book>Book 2</book>
</books>
""".encodeToByteArray().toUByteArray().toCValues()
var xmlDoc = xmlReadDoc(xml, null, null, 0)
var xsl =
"""
<xsl:stylesheet
version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='books'>
<xsl:for-each select='//book[2]'>
<xsl:sort lang='en'/>
<xsl:copy-of select='.'/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
""".encodeToByteArray().toUByteArray().toCValues()
var xslDoc = xmlReadDoc(xsl, null, null, 0)
var style = xsltParseStylesheetDoc(xslDoc)
if (style == null)
xmlFreeDoc(xslDoc)
var tctxt = xsltNewTransformContext(style, xmlDoc)
var resultDoc = xsltApplyStylesheetUser(style, xmlDoc, null, null, null, tctxt)
xsltFreeTransformContext(tctxt)
xsltSaveResultToFile(stdout, resultDoc, style)
xmlFreeDoc(resultDoc)
xsltFreeStylesheet(style)
xmlFreeDoc(xmlDoc)
}
Output
<?xml version="1.0"?>
<book>Book 2</book>
This output is based on XPath //book[2]
Thats All :)