I have used EMF to generate XSD-based access functions. I could see how to load input from a disk-file in the examples generated. However, the XML that I want to parse is stored in a string. Is there any way I can proceed without dumping the string into a file and then reading it back?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here is an example method, takes in your modelString and the ECorePackage instance that parses the xml and returns the EObject.
public static EObject loadEObjectFromString(String myModelXml, EPackage ePackage) throws IOException {
// Create a ResourceSet
ResourceSet resourceSet = new ResourceSetImpl();
// register XMIRegistryResourceFactoryIml
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put
(Resource.Factory.Registry.DEFAULT_EXTENSION,
new XMIResourceFactoryImpl());
// register your epackage to the resource set so it has a reference to your ecore
// you can get an instance to your epackage by calling YourEPackageClass.getInstace();
resourceSet.getPackageRegistry().put(ePackage.getNsURI(), ePackage);
Resource resource = resourceSet.createResource(URI.createURI("*.modelextension"));
resource.load(new URIConverter.ReadableInputStream(myModelXml), null);
// return the root model object and there you have it, all you need is to
// cast it to the right EObject based on your model
return resource.getContents().get(0);
}