// version 1.1.3
import javax.xml.parsers.DocumentBuilderFactory
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.xpath.XPathFactory
import javax.xml.xpath.XPathConstants
import org.w3c.dom.Node
import org.w3c.dom.NodeList
val xml =
"""
-
Invisibility Cream
14.50
Makes you invisible
-
Levitation Salve
23.99
Levitate yourself for up to 3 hours per application
-
Blork and Freen Instameal
4.95
A tasty meal in a tablet; just add water
-
Grob winglets
3.56
Tender winglets of Grob. Just add water
"""
fun main(args: Array) {
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
val xmlInput = InputSource(StringReader(xml))
val doc = dBuilder.parse(xmlInput)
val xpFactory = XPathFactory.newInstance()
val xPath = xpFactory.newXPath()
val qNode = xPath.evaluate("/inventory/section/item[1]", doc, XPathConstants.NODE) as Node
val upc = qNode.attributes.getNamedItem("upc")
val stock = qNode.attributes.getNamedItem("stock")
println("For the first item : upc = ${upc.textContent} and stock = ${stock.textContent}")
val qNodes = xPath.evaluate("/inventory/section/item/price", doc, XPathConstants.NODESET) as NodeList
print("\nThe prices of each item are : ")
for (i in 0 until qNodes.length) print("${qNodes.item(i).textContent} ")
println()
val qNodes2 = xPath.evaluate("/inventory/section/item/name", doc, XPathConstants.NODESET) as NodeList
val names = Array(qNodes2.length) { qNodes2.item(it).textContent }
println("\nThe names of each item are as follows :")
println(" ${names.joinToString("\n ")}")
}