我正试图通过遵循本文Is it possible to generate a XSD from a JAXB-annotated class中提到的代码从Java Annotated类生成XSD {/ 3>
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;
}
}
这种技术正在使用文件系统,我的要求是在不使用文件系统的情况下将XML作为String。
是否有可能SchemaOutputResolver
的实现可能无法将文件写入磁盘并使用String值返回或设置某个实例变量。
答案 0 :(得分:6)
您可以在StreamResult
上写下StringWriter
并从中获取字符串。
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();
}
}