Reputation: 951
I would like to load an XML schema from string using Xerces, but until now, I can only load it from an URI:
final XMLSchemaLoader xsLoader = new XMLSchemaLoader();
final XSModel xsModel = xsLoader.loadURI(file.toURI().toString());
Available methods for loading:
XSLoader {
public XSModel load(LSInput is) { }
public XSModel loadInputList(LSInputList is) { }
public XSModel loadURI(String uri) { }
public XSModel loadURIList(StringList uriList) { }
}
Is there any option to load XML schema from a string? In my context, the processing is done on client-side, so URI method cannot be used.
Thank you.
Upvotes: 3
Views: 1017
Reputation: 951
Based on @TimBiegeleisen answer I built a method for converting a string to 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);
}
Upvotes: 2
Reputation: 520878
I am not particularly familiar with your problem, but I found this useful code snippet from ProgramCreek which demonstrates how to obtain an XSModel
from an LSInput
object (the first method you listed above). It is possible to also load an XML schema from an input stream. I modified the code slightly to arrive at this:
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;
}
Usage:
// 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 ...
}
Upvotes: 2