Java Xerces-从字符串加载架构
我想使用Xerces从字符串加载XML模式,但到目前为止,我只能从URI加载它:Java Xerces-从字符串加载架构,java,xsd,schema,xerces,Java,Xsd,Schema,Xerces,我想使用Xerces从字符串加载XML模式,但到目前为止,我只能从URI加载它: final XMLSchemaLoader xsLoader = new XMLSchemaLoader(); final XSModel xsModel = xsLoader.loadURI(file.toURI().toString()); 可用的加载方法: XSLoader { public XSModel load(LSInput is) { } public XSModel loadI
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方法
谢谢。我对您的问题不是特别熟悉,但我发现了这个有用的代码片段,它演示了如何从
LSInput
对象(上面列出的第一种方法)获取XSModel
。也可以从输入流加载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 ...
}
基于@TimBiegeleisen answer,我构建了一个将字符串转换为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);
}
根据您的回答,我设法构建了一个将字符串转换为XSModel的方法。我把它贴了出来供将来参考,但投票认为你的答案被接受了。我感谢你的支持。您在问题中给出的一种方法接受了
LSInput
对象,因此诀窍是找到一种方法将文件
转换为LSInput
。使用将节省几行操作。