Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic xml conversion in scala

Tags:

scala

Let's say I have the following class:

class Person(val firstName:String, val lastName:String)

Is there an automatic way to generate xml from this class without having to hand create a toXml() method? Ideally the output would be something like:

    <Person>
        <firstName>John</firstName>
        <lastName>Smith</lastName>
    </Person>

It seems like there should be a way to do this without having to write all that out manually. Perhaps there is a trait I haven't found yet?

like image 512
Jeff Bowman Avatar asked Jun 08 '10 03:06

Jeff Bowman


2 Answers

For case classes (or other subclasses of Product), this was once very easy to write generically: the name can be retrieved with productPrefix, all values are iterable via productIterator and the names of the fields via productElementName.

Unfortunately, productElementName has only had a very short life: it was added in revision 20958 and removed in revision 21223, apparently because it added too much weight to case classes (there's also an open ticket for it).

like image 63
Mirko Stocker Avatar answered Nov 03 '22 02:11

Mirko Stocker


Unfortunately, I don't think there is such a magic trait. You could use something like XStream to accomplish this. However, it doesn't seem print all Scala classes that pretty automatically, so you probably need to write your own converter. Someone else has already done so in the case of Lists, I guess for your example you might need something similar.

like image 27
Arjan Blokzijl Avatar answered Nov 03 '22 00:11

Arjan Blokzijl