Which XML serialization library for Scala?
I'm looking for xml serialization library for 开发者_开发知识库scala. For json serialization I use lift-json, and would like my xml serialization library to be similar, that means:
- automatic serialization of case classes (without any format definition)
- smart serialization of scala types: collections, options etc.
- ability to define formats for other datatypes to adjust a way they are serialized
- deserialization not based on implicits but rather on class name (sometimes I have only class/class name of type which must be deserialized)
Do you know if such library exists?
One great alternative is to use the pure Java library XStream.
This works with case classes out of the box, with some tweaking - I'm using the class XStreamConversions from mixedbits-webframework -, it also works with List, Tuple, Symbol, ListBuffer and ArrayBuffer. So it's not perfect, but you can surely fine tune it for your specific needs.
Here is a small example.
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.StaxDriver
import net.mixedbits.tools.XStreamConversions
case class Bar(a:String)
case class Foo(a:String,b:Int,bar:Seq[Bar])
object XStreamDemo {
def main(args: Array[String]) {
val xstream = XStreamConversions(new XStream(new StaxDriver()))
xstream.alias("foo", classOf[Foo])
xstream.alias("bar", classOf[Bar])
val f0 = Foo("foo", 1, List(Bar("bar1"),Bar("bar2")))
val xml = xstream.toXML(f0)
println(xml)
val f1 = xstream.fromXML(xml)
println(f1)
println(f1 == f0)
}
}
This produces the following output:
<?xml version="1.0" ?><foo><a>foo</a><b>1</b><bar class="list"><bar><a>bar1</a></bar><bar><a>bar2</a></bar></bar></foo>
Foo(foo,1,List(Bar(bar1), Bar(bar2)))
true
For Java 1.6 / Scala 2.9 the dependencies are the xstream.jar file and the mentioned XStreamConversions class.
Try scalaxb
精彩评论