Reading and Writing XML
List<Movie> movies = new java.util.ArrayList<Movie>();
movies.add(new Movie("Casablanca", 1942));
movies.add(new Movie("Dr Zhivago", 1965));
movies.add(new Movie("Out of Africa", 1985));
MovieLibrary library = new MovieLibrary(movies);
JAXB.marshal(library, new File("/tmp/library.xml")); // write XML (more)
Result of the previous code snippet:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<movieLibrary>
<collection>
<name>Casablanca</name>
<releaseYear>1942</releaseYear>
</collection>
<collection>
<name>Dr Zhivago</name>
<releaseYear>1965</releaseYear>
</collection>
<collection>
<name>Out of Africa</name>
<releaseYear>1985</releaseYear>
</collection>
</movieLibrary>
MovieLibrary library = JAXB.unmarshal(new File("/tmp/library.xml"),
MovieLibrary.class); // read XML (more)
assert library.getCollection().size() == 3;
assert library.getCollection().get(0).getTitle().equals("Casablanca");
assert library.getCollection().get(2).getReleaseYear() == 1985;
Beside beans, JAXB supports the following types natively. Each of them can also be used either as element content or for XML attributes:
| Java type | XML Simple Schema type |
|---|---|
| java.lang.String | xs:string |
| int | xs:int |
| long | xs:long |
| boolean | xs:boolean |
| byte | xs:byte |
| short | xs:short |
| float | xs:float |
| double | xs:double |
| byte[] | xs:base64Binary |
| java.math.BigInteger | xs:integer |
| java.math.BigDecimal | xs:decimal |
| java.util.Date | xs:dateTime |
| javax.xml.namespace.QName | xs:QName |
| javax.xml.datatype.Duration | xs:duration |
Collections are also supported by JAXB and can be used as element content:
| Java type | XML Mapping |
|---|---|
| Arrays, single dimension | Repeats the element several times, sets maxOccurs in the schema to unbounded (except byte[], see above). |
| Arrays, multi dimension | For the first dimension, the item is repeated (maxOccurs in the schema set to unbounded). For additional dimensions, there is a repeating element item defined that will be nested. |
| java.util.Collection (includes List and Set) | Repeats the element several times, sets maxOccurs in the schema to unbounded (like one-dimensional arrays). |
| java.util.Map | The element contains an entry element for each Map entry (maxOccurs in the schema set to unbounded), each entry containing a key and a value element. |

