1

Context: Kotlin Multiplatform JavaScript.

I'm trying to use a Document.evaluate() but getting Unresolved reference: evaluate and Unresolved reference: XPathResult.

import org.w3c.dom.Document
import org.w3c.dom.parsing.DOMParser

object JavascriptTest {
    // language=HTML
    private val html = """
            <body>
               <div>
                  <a class="button" href="http://exaple.com">Example</a>
               </div>
            </body>
        """.trimIndent()

    fun parseXpath() {
        val parser = DOMParser()
        val document: Document = parser.parseFromString(html, "text/html")
        val xpath = "//div/a[contains(@class, \"button\")]"
        document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
    }
}

build.gradle.kts

kotlin {
    js(IR) {
        useCommonJs()
        browser {}
        binaries.executable()
    }

   sourceSets {
      val jsTest by getting
   }
vovahost
  • 34,185
  • 17
  • 113
  • 116

2 Answers2

1

As far as I know there is no bindings for XPathEvaluator interface out of the box right now. But you could add them by yourself using asDynamic:

val XPathResult = window.asDynamic().XPathResult

fun Document.evaluate(
    xpathExpression: String,
    contextNode: Node,
    namespaceResolver: Any?,
    resultType: Any,
    result: Any?
): dynamic =
    asDynamic().evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result)

Evgeny K
  • 1,744
  • 3
  • 13
  • 19
1

As an alternative to @Evgeny solution, you can also use this class which is marked as external as suggested in Use JavaScript code from Kotlin

external class XPathResult {

    companion object {
        val ANY_TYPE: Int
        val NUMBER_TYPE: Int
        val ANY_UNORDERED_NODE_TYPE: Int
        val BOOLEAN_TYPE: Int
        val FIRST_ORDERED_NODE_TYPE: Int
        val ORDERED_NODE_ITERATOR_TYPE: Int
        val ORDERED_NODE_SNAPSHOT_TYPE: Int
        val STRING_TYPE: Int
        val UNORDERED_NODE_ITERATOR_TYPE: Int
        val UNORDERED_NODE_SNAPSHOT_TYPE: Int
    }

    // Instance properties:

    val booleanValue: Boolean?
    val invalidIteratorState: Boolean
    val numberValue: Double?
    val resultType: Int
    val singleNodeValue: dynamic
    val snapshotLength: Int
    val stringValue: String?

    // Instance methods:
    fun iterateNext(): Node?

    fun snapshotItem(index: Int): Node?
}


fun Document.evaluate(
    xpathExpression: String,
    contextNode: Node,
    namespaceResolver: Any?,
    resultType: Any,
    result: Any?,
): XPathResult =
    asDynamic().evaluate(
        xpathExpression,
        contextNode,
        namespaceResolver,
        resultType,
        result
    ) as XPathResult
vovahost
  • 34,185
  • 17
  • 113
  • 116