不使用File从JAXB注释的类生成XSD

时间:2022-12-28 17:16:38

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

我试图通过以下代码中提到的代码从Java Annotated类生成XSD是否可以从JAXB注释类生成XSD

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.

这种技术使用的是File系统,我的要求是在不使用文件系统的情况下将XML作为String。

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.

是否有可能SchemaOutputResolver的实现可能无法将文件写入磁盘并返回或设置一些具有String值的实例变量。

1 个解决方案

#1


6  

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

您可以在StringWriter上编写StreamResult并从中获取字符串。

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

}

#1


6  

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

您可以在StringWriter上编写StreamResult并从中获取字符串。

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

}