Create an XML Schema of the XML Information that needs to be bound
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tst="http://www.test.org/" elementFormDefault="qualified" targetNamespace="http://www.test.org/"> <xs:element name="test"> <xs:complexType> <xs:sequence> <xs:element ref="tst:child" maxOccurs="unbounded" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="child"> <xs:complexType> <xs:attribute name="test" use="optional" default="false" type="xs:boolean"/> </xs:complexType> </xs:element> </xs:schema>
If necessary; customise the binding behavior, either by annotating the XML Schema or by specifying this in an external file.
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <jxb:bindings schemaLocation="test.xsd" node="/xs:schema"> <jxb:globalBindings bindingStyle="elementBinding" choiceContentProperty="false"/> <jxb:schemaBindings> <jxb:package name="org.test"/> </jxb:schemaBindings> </jxb:bindings> </jxb:bindings>
Create the Java Classes and Interfaces using the Binding Compiler (xjc).
java -jar jaxb\lib\jaxb-xjc.jar -extension -b test.jxb -d src -p org.test test.xsd
Compile the Java Classes and Interfaces.
javac -sourcepath src -d out *.java
Unmarshall a XML Document
JAXBContext context = JAXBContext.newInstance( "test.jaxb"); Unmarshaller unmarshaller = context.createUnmarshaller(); Collection result = (Collection)unmarshaller.unmarshal( new File( "input.xml"));
Marshall Java Objects to XML
Marshaller marshaller = context.createMarshaller(); marshaller.marshal( result, new FileOutputStream( "output.xml"));