2012-11-06 26 views
2

我已经使用EMF生成基于XSD的访问功能。我可以看到如何在生成的示例中加载来自磁盘文件的输入。但是,我想要解析的XML存储在一个字符串中。有什么方法可以在不将字符串转储到文件中然后再读回来的情况下继续进行?使用EMF以字符串格式解析XML

回答

3

下面是一个示例方法,它包含您的modelString和ECorePackage实例,该实例解析xml并返回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); 
}