我想使用Xerces从字符串加载XML模式,但到目前为止,我只能从URI加载它:
final XMLSchemaLoader xsLoader = new XMLSchemaLoader();
final XSModel xsModel = xsLoader.loadURI(file.toURI().toString());
可用的加载方法:
XSLoader {
public XSModel load(LSInput is) { }
public XSModel loadInputList(LSInputList is) { }
public XSModel loadURI(String uri) { }
public XSModel loadURIList(StringList uriList) { }
}
是否有从字符串加载XML架构的选项?在我的上下文中,处理是在客户端完成的,因此不能使用URI方法。
谢谢。
答案 0 :(得分:2)
我对您的问题并不是特别熟悉,但我发现这个有用的代码段来自ProgramCreek,它演示了如何从XSModel
对象获取LSInput
(您列出的第一种方法)以上)。也可以从输入流加载XML模式。我稍微修改了代码以达到这个目的:
private LSInput getLSInput(InputStream is) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSInput domInput = impl.createLSInput();
domInput.setByteStream(is);
return domInput;
}
<强>用法:强>
// obtain your file through some means
File file;
LSInput ls = null;
try {
InputStream is = new FileInputStream(file);
// obtain an LSInput object
LSInput ls = getLSInput(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (ls != null) {
XMLSchemaLoader xsLoader = new XMLSchemaLoader();
XSModel xsModel = xsLoader.load(ls);
// now use your XSModel object here ...
}
答案 1 :(得分:2)
根据@TimBiegeleisen的回答,我构建了一个将字符串转换为XSModel的方法。
private static XSModel getSchema(String schemaText) throws ClassNotFoundException,
InstantiationException, IllegalAccessException, ClassCastException {
final InputStream stream = new ByteArrayInputStream(schemaText.getBytes(StandardCharsets.UTF_8));
final LSInput input = new DOMInputImpl();
input.setByteStream(stream);
final XMLSchemaLoader xsLoader = new XMLSchemaLoader();
return xsLoader.load(input);
}