00.scala2014. 3. 28. 15:38
반응형

Scala XML FAQ: How do I load an XML URL in Scala? (How do I read/download the contents of an XML URL in Scala?)

To load the contents of an XML URL (web page) in Scala, such as an RSS news feed or RESTful web service, just use the load method of the Scala XML class:

val xml = XML.load("http://www.devdaily.com/rss.xml")

Here's an example of what this looks like in the Scala REPL:

scala> import scala.xml.XML
import scala.xml.XML

scala> val xml = XML.load("http://www.devdaily.com/rss.xml")
xml: scala.xml.Elem = 
<rss xml:base="http://www.devdaily.com" version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>

(output goes on for about ten more lines)

Once you have your XML object (an instance of the scala.xml.Elem class), you can search it as usual. Since my RSS feed includes an "item" tag, I can get the number of item tags in the XML contents:

scala> (xml \\ "item").length
res5: Int = 10

I can also do things like searching for "title" elements, such as getting the text from the first RSS title element:

scala> val firstTitle = (xml \\ "channel" \ "title") text
firstTitle: String = devdaily.com

As you can see, loading the contents of an XML URL in Scala is very easy.

Posted by 1010