Let's assume you have a CustomerList model, which is an array of Customer.
JAXBContext context;
try {
context = JAXBContext.newInstance(CustomerList.class);
context.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceURI,
String suggestedFileName) throws IOException {
File file = new File("c://temp//customer.xsd");
StreamResult result = new StreamResult(file);
result.setSystemId(file.toURI().toURL().toString());
return result;
}
});
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(listToExport, new FileOutputStream(
"c://temp//customers.xml"));
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Next is how are we going to read a java object from xml file. Let the code explain :-)
JAXBContext jaxbContext = JAXBContext.newInstance(CustomerList.class);
InputStream is = getClass().getClassLoader().getResourceAsStream(
"customer.xml");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
CustomerListmessages = (CustomerList) jaxbUnmarshaller.unmarshal(is);
Useful tool in transforming an xml to xsd:
http://www.freeformatter.com/xsd-generator.html#ad-output
0 nhận xét:
Đăng nhận xét