Parse XML in string format using EMF

泪湿孤枕 提交于 2019-12-11 03:11:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!