Last active
December 31, 2015 21:28
-
-
Save banshee/8046562 to your computer and use it in GitHub Desktop.
Scala IDE worksheet sample for XML
This file contains hidden or 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
| 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