Skip to content

Instantly share code, notes, and snippets.

@skryvets
Last active September 13, 2024 02:57
Show Gist options
  • Save skryvets/533e72abfdf467fa9275ac18e2f5c8af to your computer and use it in GitHub Desktop.
Save skryvets/533e72abfdf467fa9275ac18e2f5c8af to your computer and use it in GitHub Desktop.
#!/usr/bin/env kotlin
@file:Repository("https://repo.maven.apache.org/maven2/")
@file:DependsOn("com.squareup.okhttp3:okhttp:4.12.0")
import okhttp3.OkHttpClient
import okhttp3.Request
import org.w3c.dom.Document
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathFactory
// Extension function to parse XML string into a Document
fun String.parseXml(): Document {
return DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(InputSource(StringReader(this)))
}
// Extension function to evaluate XPath expression
fun Document.evaluateXPath(expression: String): String? {
return XPathFactory
.newInstance()
.newXPath()
.evaluate(expression, this)
}
val client = OkHttpClient()
val request = Request.Builder().url("https://www.w3schools.com/xml/note.xml").build();
val response = client.newCall(request).execute()
val responseBody = response.body?.string()
println("Response body: $responseBody")
// Evaluate XPath expression
val xpathExpression = ".//to"
val result = responseBody?.parseXml()?.evaluateXPath(xpathExpression)
println("XPath result: $result")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment