Skip to content

Instantly share code, notes, and snippets.

@francisco-perez-sorrosal
Created November 5, 2011 03:58
Show Gist options
  • Save francisco-perez-sorrosal/1341086 to your computer and use it in GitHub Desktop.
Save francisco-perez-sorrosal/1341086 to your computer and use it in GitHub Desktop.
Program that parses a remote XML file containing info about currencies and outputs a new user-defined format for the parsed data in a new file (passed as parameter)
package com.linkingenius.parser
import java.io.File
import java.io.FileWriter
// Handler to perform write operations in a file
case class FileHandler(file: File) {
def add(text: String): Unit = {
val fw = new FileWriter(file, true)
try { fw.write(text) }
finally { fw.close }
}
}
// Companion object for FileHandler
object FileHandler {
implicit def file2FileHelper(file: File) = FileHandler(file)
}
import java.net.URL
import scala.io.Source
import scala.xml.XML.loadString
import scala.xml.Elem
// Inmutable class representing the currency info extracted from the XML file (ISO code and currency name)
case class CurrencyInfo(code: String, name: String)
// Finally, the currency parser, which performs the required operations to parse the remote XML file
object CurrencyParser {
// Other source of info for currency codes: http://www.currency-iso.org/dl_iso_table_a1.xml
val CurrencyCodeInfoURL = "http://www.tm-xml.org/TM-XML/TM-XML_xml/ISOCurrencyCode.xml"
// User defined format for output
val CurrencyOutput = "Currency code: %s - Currency name: %s\n"
def main(args: Array[String]) {
writeToFile(args(0), getCodesAndNamesFromCurrencies(loadString(getURLAsString(CurrencyCodeInfoURL))))
}
private def getURLAsString(url: String): String = Source.fromURL(new URL(url)).mkString
private def getCodesAndNamesFromCurrencies(currencyInfoXML: Elem): Seq[CurrencyInfo] = {
currencyInfoXML match {
case <ISOCurrencyCode>{ currencies @ _* }</ISOCurrencyCode> =>
for {
currency @ <Currency>{ _* }</Currency> <- currencies
code = (currency \ "CurrencyCode").text
name = (currency \ "CurrencyName").text
} yield CurrencyInfo(code, name)
case _ => Seq()
}
}
private def writeToFile(outputFileName: String, codesAndNames: Seq[CurrencyInfo]): Unit = {
import FileHandler._
val f = new File(outputFileName)
f.delete
codesAndNames map { ci => f.add(CurrencyOutput.format(ci.code, ci.name)) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment