no

How to create an xsd and xml data from model entity in java

The following code will show how to generate a xsd base on a given model and a sample xml with data. Let's assume you have a CustomerL...

The following code will show how to generate a xsd base on a given model and a sample xml with data.

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

Related

java 4607580066512806864

Post a Comment

item