-
Notifications
You must be signed in to change notification settings - Fork 92
Getting started
Aaron S. Hawley edited this page Oct 13, 2017
·
24 revisions
The following documentation assumes you're familliar with and already using both the Scala programminag language and the sbt build tool:
In Scala 2.11 and later, add the following to your build.sbt
file's libraryDependencies
:
"org.scala-lang.modules" %% "scala-xml" % "1.0.6"
You can query XML values with an XPath-like syntax:
val id = book \@ "id"
id: String = b20234
val text = book.text
text: String = Magic of scala-xml
XML more often has sub-elements:
val books = <books>
<book id="b1615">Don Quixote</book>
<book id="b1867">War and Peace</book>
</books>
Retrieving the child elements is possible, but a little more complicated:
val titles = (books \ "book").map(_.text).toList
titles: List[String] = List(Don Quixote, War and Peace)
Many return types of scala-xml are are Scala collections. If you aren't familiar with Scala collections, you should read the documentation for Scala collections.
Finding the text of an XML element by its id
val quixote = (books \ "book").find(book => (book \@ "id") == "b1615").map(_.text)
quixote: Option[String] = Some(Don Quixote)
To open XML from files use scala.xml.XML
:
val books = scala.xml.XML.loadFile("books.xml")