我如何在 jaxb 中解组并在不使用显式模式文件的情况下享受模式验证
我将 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
相关文章