Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pojo to xsd generation

Tags:

java

xml

pojo

xsd

Is there a library which could generate a xsd schema from a java class? Google yields lots of results the opposite ( java classes from xsd ).

like image 521
Surya Avatar asked Aug 24 '09 22:08

Surya


2 Answers

JAXB 2.0 allows you to create a XML schema from an annotated Java class.

You'll find some examples at the AMIS blog and at the JavaPassion site.

like image 103
Vineet Reynolds Avatar answered Sep 28 '22 08:09

Vineet Reynolds


Here is how I would do it:

public static void pojoToXSD(Class<?> pojo, OutputStream out) throws IOException, TransformerException, JAXBException {
    JAXBContext context = JAXBContext.newInstance(pojo);
    final List<DOMResult> results = new ArrayList<>();

    context.generateSchema(new SchemaOutputResolver() {

        @Override
        public Result createOutput(String ns, String file)
                throws IOException {
            DOMResult result = new DOMResult();
            result.setSystemId(file);
            results.add(result);
            return result;
        }
    });

    DOMResult domResult = results.get(0);

    // Use a Transformer for output
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(domResult.getNode());
    StreamResult result = new StreamResult(out);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(source, result);
}

How to use the method above

try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        pojoToXSD(NESingleResponse.class, stream);

        String finalString = new String(stream.toByteArray());
        System.out.println(finalString);
    } catch (JAXBException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
like image 24
ra9r Avatar answered Sep 28 '22 08:09

ra9r