running scalaxb
This page describes how to use scalaxb
once you have installed it on your machine. (See setup)
running
You need a XML Schema definition file, or .xsd file for short.
Suppose you have usaddress.xsd:
<xs:schema targetNamespace="http://www.example.com/IPO"
elementFormDefault="qualified"
xmlns="http://www.example.com/IPO"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:ipo="http://www.example.com/IPO">
<xs:complexType name="Address">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="USAddress">
<xs:complexContent>
<xs:extension base="ipo:Address">
<xs:sequence>
<xs:element name="state" type="xs:string"/>
<xs:element name="zip" type="xs:positiveInteger"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
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="http://scalaxb.org/">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="http://www.example.com/IPO"> <name>Foo</name> <street>1537 Paper Street</street> <city>Wilmington</city> </shipTo> 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="http://www.example.com/IPO">
<name>Foo</name>
<street>1537 Paper Street</street>
<city>Wilmington</city>
</shipTo>
subject: scala.xml.Elem =
<shipTo xmlns="http://www.example.com/IPO">
<name>Foo</name>
<street>1537 Paper Street</street>
<city>Wilmington</city>
</shipTo>
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="http://www.example.com/IPO" xmlns:ipo="http://www.example.com/IPO" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><name>Bar</name><street>1537 Paper Street</street><city>Wilmington</city></foo>