問題描述
我將 jaxb 用于我的應(yīng)用程序配置
I am using jaxb for my application configurations
我覺得我在做一些非常不正當(dāng)?shù)氖虑椋艺趯ふ乙环N不需要實(shí)際文件或此交易的方法.
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 中創(chuàng)建一個(gè)模式到一個(gè)文件中(實(shí)際上來自我的類??注釋)2.設(shè)置此模式文件以便在我解組時(shí)允許真正的驗(yàn)證
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(...);
你們中有人知道如何驗(yàn)證 jaxb,而無需在我的計(jì)算機(jī)中創(chuàng)建架構(gòu)文件嗎?
do any of you know how I can validate jaxb without needing to create a schema file that sits in my computer?
我是否需要?jiǎng)?chuàng)建一個(gè)模式進(jìn)行驗(yàn)證,當(dāng)我通過 JaxbContect.generateSchema 獲得它時(shí)它看起來是多余的?
Do I need to create a schema for validation, it looks redundant when I get it by JaxbContect.generateSchema ?
你是怎么做到的?
推薦答案
關(guān)于上面ekeren的解決方案,在單線程中使用PipedOutputStream/PipedInputStream并不是一個(gè)好主意,以免溢出緩沖區(qū)導(dǎo)致死鎖.ByteArrayOutputStream/ByteArrayInputStream 有效,但如果您的 JAXB 類生成多個(gè)模式(在不同的命名空間中),您需要多個(gè) 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.
我最終得到了這個(gè):
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
這篇關(guān)于我如何在 jaxb 中解組并在不使用顯式模式文件的情況下享受模式驗(yàn)證的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!