8月 282011
 

■csv2xml.groovy


import java.io.InputStreamReader
import au.com.bytecode.opencsv.CSVReader
import scala.collection.mutable.Queue
import scala.xml.Node
import scala.xml.PrettyPrinter

object Csv2Xml {
  def main(args: Array[String]): Unit = {
    var nodes = new Queue[Node]()
    
    var reader = new CSVReader(new InputStreamReader(System.in, "UTF-8"),',','"',' ',1)
    Iterator.continually(reader.readNext).takeWhile(_ != null).map(_.toList).foreach {
      case id :: name :: price :: _ =>  nodes += <item id={id}><name>{name}</name><price>{price}</price></item>
      case _ => 
    }
    reader.close()
    
    print((new PrettyPrinter(40,2)).format(<xml><items>{nodes}</items></xml>))
  }
}

■source.csv(UTF-8)
————————————————–
id, name, price
1, コーラ, 150
2, 葡萄酒, 980
3, 麦酒, 238

————————————————–

■実行
scala -cp opencsv-2.3.jar csv2xml.scala < source.csv

■結果(標準出力)
————————————————–
<xml>
  <items>
    <item id=”1″>
      <name>コーラ</name>
      <price>150</price>
    </item>
    <item id=”2″>
      <name>葡萄酒</name>
      <price>980</price>
    </item>
    <item id=”3″>
      <name>麦酒</name>
      <price>238</price>
    </item>
  </items>
</xml>
————————————————–

Sorry, the comment form is closed at this time.