Xerces - 从字符串加载模式

3

我希望能够使用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方法。
谢谢。
2个回答

2

我对你的问题不是特别熟悉,但我在ProgramCreek找到了这个有用的代码片段,展示了如何从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 ...
}

根据您的答案,我成功构建了一个将字符串转换为XSModel的方法。我将其发布供日后参考,但已选定您的答案作为最佳答案。 - nucandrei
1
我感谢您的支持。在您的问题中提供的方法之一接受了一个LSInput对象,所以关键是找到一种将File转换为LSInput的方法。 - Tim Biegeleisen
使用LSInput.setStringData可以节省几行代码。 - Matthias

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接