Quando eu trabalhei em um grande projeto na Caixa em Brasília, usavamos o JAXB 1.x para fazer o data binding(marshall/unmarshall) de objetos Java para XML e vice-versa.
Componentes como o XStream da CodeHaus, facilitam bastante a vida, mas ainda é complicado dependendo do cliente homologar uma solução como esta. Sendo assim, vamos ao padrão, já que o JAXB faz parter do WebService Developer Pack, ou seja: Padrão estabelecidos em JSR e controlado pelos mebros no JCP, entre as principais melhorias, podemos citar:
- Bibliotecas de Runtime menores economizando assim no uso de memória.
- Muito menos classes são geradas se compararmos com o JAXB1.0. Para cada tipo complexo, a nova versão gera uma classe para direto ao invés de criar uma interface e uma implementação.
- Suporte a todos os tipos de XML Schema.
- Adição de tipos parametrizados.
- Suporte a bind Java-to-XML com as anotações do pacote: javax.xml.bind.annotation package.
Sendo assim, vamos a um pequeno tutorial, para mostrar como pode ser simples realizar o binding de objeto para XML e vice versa.
- Faça o Downlaod do JAXB no site: http://jaxb.dev.java.net
- Execute o JAR que é o instalador: java -jar jaxb
.jar e instale num lugar do tipo /opt/java/jaxb ou c:/java/jaxb - Não vou citar IDE’s, por isso criei toda uma estrutura baseada em ANT, sendo assim criei um arquivo chamdo de build.properties[1] que fornece informações para o build.xml, já que há uma TASK do JAXB, entao vamos usá-la para que esta realize as tarefas que desejamos, que é gerar as classes que vão estar visíveis pro contexto do JAXB[2].
- A Estrutura do projeto é simples:
- src (pasta com fontes)
- gen-src (pasta com os fontes gerados pelo JAXB)
- classes (pasta com as classes compiladas)
- schema (caso você queira guardar os XSD’s aqui[3])
- lib (pasta com bibliotecas)
Referências
1 - build.properties
[java]
xsd.file=transaction.xsd
package.name=br.com.acme.entidades
jaxb.home=/Users/edgarsilva/java/jaxb/jaxb-ri-20070125
[/java]
2 - O build.xml (Script ANT)
[xml]
< ?xml version="1.0" standalone="yes"?>
This sample app demonstrates how a pull-parser can
be used with JAXB to increase the flexibility of processing.
Please download sjsxp.jar from the web and place it in the lib directory.
3 - O XML Schema transaction.xsd
[xml]
< ?xml version="1.0"?>
[/xml]
4 - A classe gerada pelo JAXB 2.0
[java]
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.2-b01-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2007.03.23 at 05:00:55 PM BRT
//
package br.com.acme.entidades;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*Java class for anonymous complex type.
*
*The following schema fragment specifies the expected content contained within this class.
*
*
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="objectAsXML" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="returnAsXML" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = “”, propOrder = {
“name”,
“objectAsXML”,
“returnAsXML”
})
@XmlRootElement(name = “transaction”)
public class Transaction {
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String objectAsXML;
@XmlElement(required = true)
protected String returnAsXML;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the objectAsXML property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getObjectAsXML() {
return objectAsXML;
}
/**
* Sets the value of the objectAsXML property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setObjectAsXML(String value) {
this.objectAsXML = value;
}
/**
* Gets the value of the returnAsXML property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReturnAsXML() {
return returnAsXML;
}
/**
* Sets the value of the returnAsXML property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReturnAsXML(String value) {
this.returnAsXML = value;
}
}
[/java]
5 - A Classe Main para testar isso funcionando:
[java]
public static void main(String[] args) {
try {
// create a JAXBContext capable of handling classes generated into
// the primer.po package
JAXBContext jc = JAXBContext.newInstance( “br.com.acme.entidades” );
Transaction trans = new Transaction();
trans.setName(”ANALISAR_CREDITO”);
trans.setObjectAsXML(”TESTE”);
// create a Marshaller and marshal to a file
Marshaller m = jc.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.marshal( trans, System.out );
} catch( JAXBException je ) {
je.printStackTrace();
}
}
[/java]


Entries (RSS)