Skip to content

Instantly share code, notes, and snippets.

@banshee
Last active December 31, 2015 21:28
Show Gist options
  • Select an option

  • Save banshee/8046562 to your computer and use it in GitHub Desktop.

Select an option

Save banshee/8046562 to your computer and use it in GitHub Desktop.
Scala IDE worksheet sample for XML
import scala.xml._
object SampleWorksheet {
// Some simple xml
val xml = """
<cone style="waffle" sprinkles="red">
tasty!!
<scoop size="small" />
<scoop size="large" />
</cone>
""" //> xml : String = "
//| <cone style="waffle" sprinkles="red">
//| tasty!!
//| <scoop size="small" />
//| <scoop size="large" />
//| </cone>
//| "
// --------------------------------------------------------------------------------------------
// Process it
val x = XML.loadString(xml) //> x : scala.xml.Elem = <cone sprinkles="red" style="waffle">
//| tasty!!
//| <scoop size="small"/>
//| <scoop size="large"/>
//| </cone>
// --------------------------------------------------------------------------------------------
// cone is the label, tasty!! is the text, and there's an attributes collection.
// Notice the whitespace in the text may not be quite what you expect.
x.label //> res0: String = cone
x.text //> res1: String = "
//| tasty!!
//|
//|
//| "
x.attributes //> res2: scala.xml.MetaData = sprinkles="red" style="waffle"
x.attributes.map { x => (x.key, x.value, x.value.text) }
//> res3: Iterable[(String, Seq[scala.xml.Node], String)] = List((sprinkles,red,
//| red), (style,waffle,waffle))
x.child //> res4: scala.xml.Node* = List(
//| tasty!!
//| , <scoop size="small"/>,
//| , <scoop size="large"/>,
//| )
// Notice that you can have text children
// that you might not care about
x.child.map { _.getClass } //> res5: Seq[Class[_ <: scala.xml.Node]] = List(class scala.xml.Text, class sca
//| la.xml.Elem, class scala.xml.Text, class scala.xml.Elem, class scala.xml.Tex
//| t)
for {
a <- x.child if a.isInstanceOf[scala.xml.Elem]
} yield a //> res6: Seq[scala.xml.Node] = List(<scoop size="small"/>, <scoop size="large"/
//| >)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment