13 August, 2009

Bind XML to Java classes

Just follow this example:

<ValCurs Date="30/05/2009" name="Foreign Currency Market">
<Valute ID="R01035">
<Name>Фунт стерлингов Соединенного королевства</Name>
<Valute ID="R01235">
<Name>Доллар США</Name>
<Valute ID="R01239">

package xqx;

import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "ValCurs")
@XmlType(name = "ValCursType")
public class ValCursType {

@XmlElement(name = "Valute")
public List<ValuteType> valuteType;

@XmlAttribute(name = "Date")
public String date;

public String name;

package xqx;

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "Valute")
@XmlType(name = "ValuteType")
public class ValuteType {
@XmlElement(name = "NumCode")
public String numCode;

@XmlElement(name = "CharCode")
public String charCode;

@XmlElement(name = "Nominal")
public int nominal;

@XmlElement(name = "Name")
public String name;

@XmlElement(name = "Value")
public String value;

@XmlAttribute(name = "ID")
public String id;

package xqx;

import ...;

public class CbrCurrencyTask {

//stream - For example FileInputStream created from the "cbr_daily.xml" file
protected ValCursType parse(InputStream stream) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(ValCursType.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

ValCursType valCursType = (ValCursType) unmarshaller.unmarshal(stream);
return valCursType;


Simple! Isn't it?

No comments: