Per prima cosa bisogna includere nel Build Path del progetto i seguenti JAR:
- com.springsource.com.sun.tools.xjc-2.1.7.jar
- com.springsource.com.sun.xml.bind-2.1.7.jar
- com.springsource.javax.xml.bind-2.1.7.jar
1. scriviamo un XML, per esempio:
<?xml version="1.0" encoding="UTF-8"?>
<libri>
<libro pagine="20">
<titolo>Java Base</titolo>
</libro>
<libro>
<titolo>VB6 Base</titolo>
<autore>Jemma Oconnel</autore>
</libro>
</libri>
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Libri.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("./file/libri.xml");
//XML to Java Classes
Libri libri = (Libri) unmarshaller.unmarshal(xml);
for (Libro item : libri.getLibro()) {
System.out.println(item.getTitolo());
System.out.println(item.getAutore());
System.out.println("-----------------");
}
//Java Classes to XML
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//direttamente in Output
marshaller.marshal(libri, System.out);
System.out.println("");
//memorizzazione in stringa
StringWriter sw = new StringWriter();
marshaller.marshal(libri, sw);
System.out.println(sw);
}