Skip to content

Instantly share code, notes, and snippets.

@aya-eiya
Created March 19, 2011 16:56
Show Gist options
  • Save aya-eiya/877609 to your computer and use it in GitHub Desktop.
Save aya-eiya/877609 to your computer and use it in GitHub Desktop.
Converting Map objects in List to XML
package personal.ayaeiya.scala.sample
import scala.xml._
case class ListEndDummy{}
case class MapEndDummy{}
object Main{
def main(args:Array[String]) = {
def toXml(list:List[Any]):Elem = {
val lst = list ::: List(ListEndDummy)
XML.loadString(lst.foldLeft("<list>"){ (s,m) =>
s + (m match {
case map:Map[String,Any] => toNode(map)
case ListEndDummy => "</list>"
})
})
}
def toNode(map:Map[String,Any]):String = {
// Hold sort & Add dummy
val m = map.toList ::: List(("dmy",MapEndDummy))
m.foldLeft(("xml","<map>")){
(st1,st2) =>
("xml",
st1._2 +
(st2._2 match {
case v:String => "<" + st2._1+">" + v + "</"+st2._1+">"
case MapEndDummy => "</map>"
case v:Map[String,Any] => "<" + st2._1+">" + toNode(v) + "</"+st2._1+">"
case _=> "<other />"
})
)
}._2
}
val mp = List(
Map("Key0"->"Value0"),
Map("Key1"->"Value1","Key1-2"->"Value1-2"),
Map("Key2"->Map("Key2-1"->"Value2-1","Key2-2"->"Value2-2"),
"Key3"->Map("Key3-1"->"Value3-1","Key3-2"->"Value3-2"))
)
println(toXml(mp))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment