<?xml version="1.0" encoding="UTF-8" ?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://jaxb.sample" xmlns:ns="http://jaxb.sample"> <xsd:element name="accounts" type="ns:accounts"> </xsd:element> <xsd:complexType name="accounts"> <xsd:sequence> <xsd:element name="data" type="ns:data" minOccurs="0" maxOccurs="unbounded" /> </xsd:sequence> </xsd:complexType> <xsd:complexType name="data"> <xsd:sequence> <xsd:element name="cost" type="xsd:long" /> <xsd:element name="comment" type="xsd:string" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="date" type="xsd:date" /> </xsd:complexType> </xsd:schema>
> xjc accounts.xsd
以下の4つのファイルができる
public class Jaxb {
private JAXBContext jc;
private ObjectFactory factory = new ObjectFactory();
public Jaxb() throws JAXBException {
jc = JAXBContext.newInstance("sample.jaxb");
}
public void write(Accounts accounts, String fileName) throws JAXBException,FileNotFoundException {
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
FileOutputStream fo = new FileOutputStream(new File(fileName));
JAXBElement<Accounts> element = factory.createAccounts(accounts);
try {
marshaller.marshal(element, fo);
} finally {
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Accounts read(File xmlFile) throws JAXBException{
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Accounts> o = (JAXBElement<Accounts>) unmarshaller.unmarshal(xmlFile);
return o.getValue();
}
public static Data getData(String comment, long cost, Date date) throws DatatypeConfigurationException {
// Date => XmlGregorianCalender
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
DatatypeFactory factory = DatatypeFactory.newInstance();
XMLGregorianCalendar xgc = factory.newXMLGregorianCalendar(gc);
Data data = new Data();
data.setComment(comment);
data.setCost(cost);
data.setDate(xgc);
return data;
}
public static void main(String[] args) throws JAXBException, DatatypeConfigurationException, FileNotFoundException {
Jaxb jaxb = new Jaxb();
Accounts accounts = new Accounts();
accounts.getData().add(Jaxb.getData("朝飯", 150, new Date()));
accounts.getData().add(Jaxb.getData("昼飯", 500, new Date()));
accounts.getData().add(Jaxb.getData("晩飯", 1000, new Date()));
jaxb.write(accounts, "sample.xml");
Accounts accounts2 = jaxb.read(new File("sample.xml"));
for(Data data : accounts2.getData()){
System.out.println(data.getComment()+ ":"+ data.getCost());
}
}
}