Scala XML Serialization and Deserialization using ScalaXB

. 2 min read

Howdy folks! Coming from Java world, it has always been using JAXB to creating annotated classes to convert XML from and to Java classes. While that has been a lot of work, Scalaxb provides convenient tools for scala XML serialization and deserialization.

Here, we are going to use one such example using Scalaxb. Scalaxb describes itself as:

Scalaxb is an XML data-binding tool for Scala that supports W3C XML Schema (XSD) and Web Services Description Language (WSDL) as the input file.

Yeah, as you can see it is an XML data binding tool for Scala This means that given an XML, it makes it super easy to create data bindings by generating respective classes and helper utilities to convert to and from XML.

Here’s an example XSD, we are going to use for this example.

Setting up Scalaxb

Let’s get started by installing Scalaxb tool for generating required helper utilities for transformation and required case classes. We are using Conscript here, which helps accelerate adding Scala apps to the system. Conscript does the heavy lifting for you and adds a Scalaxb binary to the classpath.

Using Scalaxb to create XML bindings and helper utilities

Scalaxb provides convenient command line options to generate the required case classes. We use this command for code generation. The -p option allows us to provide the required package name and the option -d option can be used for the destination directory.

This generates the required case classes for holding the data, the protocol and helpers defining the transformation routines.

Serializing and Deserializing XML to and from Scala Case Classes

Once you have appropriate code generated, its heck of an easy task to convert to and from XML. Following Code, snippets give an example.

The complete code of this example is added to GitHub in the following repository. Also, Scalaxb relies on Scala XML and Scala Parser Combinators to your classpath in case you are using Scala >= 2.11