問題描述
我將 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 中解組并在不使用顯式模式文件的情況下享受模式驗證的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!