如何使用Kotlin JS访问XPath解析。

huangapple go评论48阅读模式
英文:

How to access xpath parsing using Kotlin JS

问题

我正在尝试使用 Kotlin JS 进行实验,然后将其用于项目中。
我想要使用用户被提示上传到站点的 xpath 规范来解析 HTML 文档。

import kotlinx.browser.document

val h1 = document.asDynamic().evaluate("//h1", getDocument())
println("xpath h1=${h1}")
return h1

在浏览器控制台窗口中,println 显示 xpath h1=[object XPathResult]

两个问题:

  1. 在 Kotlin JS 中,evaluate() 是用于 XPath 解析的好方法吗?

  2. 在 Kotlin JS 中,XPathResult 是在哪里定义的?Intellij 没有提供添加适当导入的选项。

英文:

I'm experimenting with Kotlin JS before using it in a project.
I'd like to parse a HTML doc using xpath specifications that the user is prompted to upload to the site.

    import kotlinx.browser.document

    val h1 = document.asDynamic().evaluate("//h1", getDocument())
    println("xpath h1=${h1}")
    return h1

In a browser console window, the println displays xpath h1=[object XPathResult]

Two questions:

  1. is …evaluate() a good approach for XPath parsing in Kotlin JS?

  2. where is XPathResult defined in Kotlin JS? Intellij doesn't offer to add an appropriate import.

答案1

得分: 0

  1. asDynamic().evaluate 是常用的方法;然而,有定制的封装器 [1] 可以使事情更具类型安全性
  2. 正如 '使用 Kotlin 中的 JavaScript 代码' 所述

> 你可以通过动态类型自由地从 Kotlin 向 JavaScript 进行交互。如果
> 你想要充分利用 Kotlin 类型系统的威力,你可以
> 为 JavaScript 库创建外部声明,这些声明将被
> Kotlin 编译器和周围的工具理解。...

> 要告诉 Kotlin 某个声明是纯
> JavaScript 编写的,应该用 external 修饰符标记它。

这是一个示例,展示了在 Kotlin 中导入 XPathResult 作为外部对象时可能的样子。

英文:
  1. asDynamic().evaluate is the common approach; however, there are custom wrappers [1] to make things more type-safe
  2. As stated in 'Use JavaScript code from Kotlin'

> You can freely talk to JavaScript from Kotlin via dynamic types. If
> you want to use the full power of the Kotlin type system, you can
> create external declarations for JavaScript libraries which will be
> understood by the Kotlin compiler and the surrounding tooling. ...

> To tell Kotlin that a certain declaration is written in pure
> JavaScript, you should mark it with the external modifier.

Here's an example of how this could look like when you import XPathResult as an external object in kotlin.

huangapple
  • 本文由 发表于 2023年6月8日 01:58:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定