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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With