XML/XPath: Difference between revisions

Content added Content deleted
m (→‎{{header|Nim}}: Use the correct template)
(→‎{{header|Scala}}: Replace with code that follow XPath semantics and the problem description more closely)
Line 2,771: Line 2,771:
| </inventory>
| </inventory>


scala> val firstItem = for {
scala> val firstItem = xml \\ "item" take 1
firstItem: scala.xml.NodeSeq =
| firstSection <- (xml \ "section").headOption
NodeSeq(<item upc="123456789" stock="12">
| firstItem <- (firstSection \ "item").headOption
<name>Invisibility Cream</name>
| } yield firstItem
<price>14.50</price>
firstItem: Option[scala.xml.Node] =
<description>Makes you invisible</description>
Some(<item upc="123456789" stock="12">
</item>)
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>)


scala> val prices = for {
scala> xml \\ "price" foreach println
<price>14.50</price>
| section <- (xml \ "section")
<price>23.99</price>
| item <- (section \ "item")
| price <- (item \ "price")
<price>4.95</price>
<price>3.56</price>
| } yield scala.math.BigDecimal(price.text)
prices: List[scala.math.BigDecimal] = List(14.50, 23.99, 4.95, 3.56)


scala> val salesTax = prices.sum * 0.05
scala> val names = (xml \\ "name").toArray
names: Array[scala.xml.Node] = Array(<name>Invisibility Cream</name>, <name>Levitation Salve</name>, <name>Blork and Freen Instameal</name>, <name>Grob winglets</name>)
salesTax: scala.math.BigDecimal = 2.3500

scala> println(salesTax.setScale(2, BigDecimal.RoundingMode.HALF_UP))
2.35

scala> val names = for {
| section <- (xml \ "section").toArray
| item <- (section \ "item")
| name <- (item \ "name")
| } yield name.text
names: Array[String] = Array(Invisibility Cream, Levitation Salve, Blork and Freen Instameal, Grob winglets)</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==