我正在使用jaxb进行应用程序配置
我觉得我正在做一些非常歪曲的事情,我正在寻找一种不需要实际文件或此交易的方法.
正如您在代码I中看到的:
1.从我的JaxbContext(实际上来自我的类注释)创建一个模式到一个文件中2.设置这个模式文件,以便在我解组时允许真正的验证
JAXBContext context = JAXBContext.newInstance(clazz);
Schema mySchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
jaxbContext.generateSchema(new MySchemaOutputResolver()); // ultimately creates schemaFile
Unmarshaller u = m_context.createUnmarshaller();
u.setSchema(mySchema);
u.unmarshal(...);
Run Code Online (Sandbox Code Playgroud)
你们中的任何人都知道如何在不需要创建位于我的计算机中的模式文件的情况下验证jaxb吗?
我是否需要创建用于验证的模式,当我通过JaxbContect.generateSchema获取它时,它看起来是多余的?
你怎么做到这一点?
sea*_*anf 13
关于上面的ekeren解决方案,在单个线程中使用PipedOutputStream/PipedInputStream不是一个好主意,以免溢出缓冲区并导致死锁.ByteArrayOutputStream/ByteArrayInputStream可以工作,但如果您的JAXB类生成多个模式(在不同的名称空间中),则需要多个StreamSource.
我最终得到了这个:
JAXBContext jc = JAXBContext.newInstance(Something.class);
final List<ByteArrayOutputStream> outs = new ArrayList<ByteArrayOutputStream>();
jc.generateSchema(new SchemaOutputResolver(){
@Override
public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
outs.add(out);
StreamResult streamResult = new StreamResult(out);
streamResult.setSystemId("");
return streamResult;
}});
StreamSource[] sources = new StreamSource[outs.size()];
for (int i=0; i<outs.size(); i++) {
ByteArrayOutputStream out = outs.get(i);
// to examine schema: System.out.append(new String(out.toByteArray()));
sources[i] = new StreamSource(new ByteArrayInputStream(out.toByteArray()),"");
}
SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
m.setSchema(sf.newSchema(sources));
m.marshal(docs, new DefaultHandler()); // performs the schema validation
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22918 次 |
最近记录: |