我在应用程序配置中使用jaxb
我感觉自己在做某些真正歪曲的事情,我正在寻找一种不需要实际文件或事务的方法。
如您在代码中看到的,我:
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(...);
你们中的任何人都知道我如何可以验证jaxb而不需要创建计算机中的架构文件吗?
我是否需要创建一个验证模式,当通过JaxbContect.generateSchema获得它时,它看起来是多余的?
你怎么做到这一点?
对于上面的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句