如何在jaxb中解组并享受模式验证而不使用显式模式文件 [英] how can i unmarshall in jaxb and enjoy the schema validation without using an explicit schema file
问题描述
我正在使用jaxb进行我的应用程序配置
I am using jaxb for my application configurations
我觉得我正在做一些非常歪曲的事情,我正在寻找一种不需要实际文件的方法交易。
I feel like I am doing something really crooked and I am looking for a way to not need an actual file or this transaction.
正如你在代码I中看到的那样:
As you can see in code I:
1.从我的文件中创建一个模式JaxbContext(实际来自我的类注释)
2.设置此模式文件以便在我解组时允许真正的验证
1.create a schema into a file from my JaxbContext (from my class annotation actually) 2.set this schema file in order to allow true validation when I unmarshal
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而不需要创建一个位于我的模式文件中计算机?
do any of you know how I can validate jaxb without needing to create a schema file that sits in my computer?
我是否需要创建一个用于验证的模式,当我通过JaxbContect.generateSchema获取它时看起来多余?
Do I need to create a schema for validation, it looks redundant when I get it by JaxbContect.generateSchema ?
你是怎么做到的?
推荐答案
关于上面的ekeren解决方案,使用PipedOutputStream / PipedInputStream不是一个好主意在一个线程中,以免溢出缓冲区并导致死锁。 ByteArrayOutputStream / ByteArrayInputStream可以工作,但如果您的JAXB类生成多个模式(在不同的名称空间中),则需要多个StreamSource。
Regarding ekeren's solution above, it's not a good idea to use PipedOutputStream/PipedInputStream in a single thread, lest you overflow the buffer and cause a deadlock. ByteArrayOutputStream/ByteArrayInputStream works, but if your JAXB classes generate multiple schemas (in different namespaces) you need multiple StreamSources.
我最终得到了这个:
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
这篇关于如何在jaxb中解组并享受模式验证而不使用显式模式文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!