running scalaxb

This page describes how to use scalaxb once you have installed it on your machine. (See setup)


You need a XML Schema definition file, or .xsd file for short.
Suppose you have usaddress.xsd:

<xs:schema targetNamespace=""
  <xs:complexType name="Address">
      <xs:element name="name"   type="xs:string"/>
      <xs:element name="street" type="xs:string"/>
      <xs:element name="city"   type="xs:string"/>

  <xs:complexType name="USAddress">
      <xs:extension base="ipo:Address">
          <xs:element name="state" type="xs:string"/>
          <xs:element name="zip"   type="xs:positiveInteger"/>

You then run the following:

$ scalaxb usaddress.xsd -p ipo

-p ipo specifies the package name. scalaxb should generate three sources.
First is usaddress.scala that contains case classes that represents the complex types:

// Generated by <a href="">scalaxb</a>.
package ipo
trait Addressable {
  val name: String
  val street: String
  val city: String
case class Address(name: String,
  street: String,
  city: String) extends Addressable
case class USAddress(name: String,
  street: String,
  city: String,
  state: String,
  zip: Int) extends Addressable

Next, it generates xmlprotocol.scala, which defines the typeclass contracts wrapped up in XMLProtocol trait and typeclass instances to convert XML into case classes. Finally, scalaxb generates scalaxb.scala, which defines scalaxb package object and other helper classes.

quick demo

Here's an example of how you could use the generated code:

val subject = <shipTo xmlns="">
  <street>1537 Paper Street</street>
val shipTo = scalaxb.fromXML[ipo.Address](subject)
val document = scalaxb.toXML[ipo.Address](shipTo.copy(name = "Bar"), None, Some("foo"), ipo.defaultScope)

Let's look at this in the REPL:

scala> val subject = <shipTo xmlns="">
        <street>1537 Paper Street</street>
subject: scala.xml.Elem = 
<shipTo xmlns="">
  <street>1537 Paper Street</street>

scala> val shipTo = scalaxb.fromXML[ipo.Address](subject)
shipTo: ipo.Address = Address(Foo,1537 Paper Street,Wilmington)

scala> val document = scalaxb.toXML[ipo.Address](shipTo.copy(name = "Bar"), None, Some("foo"), ipo.defaultScope) 
document: scala.xml.NodeSeq = <foo xmlns="" xmlns:ipo="" xmlns:xs="" xmlns:xsi=""><name>Bar</name><street>1537 Paper Street</street><city>Wilmington</city></foo>