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

╄→尐↘猪︶ㄣ 提交于 2020-05-26 06:29:05

问题


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.


回答1:


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();
    }

}


来源:https://stackoverflow.com/questions/24038802/generate-a-xsd-from-a-jaxb-annotated-class-without-using-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!