Parse XML in string format using EMF

2019-07-15 16:50发布

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条回答
来,给爷笑一个
2楼-- · 2019-07-15 17:27

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);
}
查看更多
登录 后发表回答