问题
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);
}
来源:https://stackoverflow.com/questions/13249987/parse-xml-in-string-format-using-emf