Generate a XSD from a JAXB-annotated class without using File

java, jaxb, xml, xsd

Solution

You can write the `StreamResult` on a `StringWriter` and get the string from that.

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
MySchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);
String schema = sor.getSchema();

public class MySchemaOutputResolver extends SchemaOutputResolver {
    private StringWriter stringWriter = new StringWriter();    

    public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException  {
        StreamResult result = new StreamResult(stringWriter);
        result.setSystemId(suggestedFileName);
        return result;
    }

    public String getSchema() {
        return stringWriter.toString();
    }

}

Problem

I am trying to generate XSD from Java Annotated classes by following code mentioned in this post Is it possible to generate a XSD from a JAXB-annotated class ``` JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); SchemaOutputResolver sor = new MySchemaOutputResolver(); jaxbContext.generateSchema(sor); public class MySchemaOutputResolver extends SchemaOutputResolver { public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException { File file = new File(suggestedFileName); StreamResult result = new StreamResult(file); result.setSystemId(file.toURI().toURL().toString()); return result; } } ``` This technique is using File system, My requirement is to get the XML as String without using file system. Is there any possibility the Implementation of `SchemaOutputResolver` may not write file to disk and return or set some instance variable with the String value.

Original source

Related problems