Last active
September 13, 2024 02:57
-
-
Save skryvets/533e72abfdf467fa9275ac18e2f5c8af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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