我使用 EMF 来生成基于 XSD 的访问函数。我可以在生成的示例中看到如何从磁盘文件加载输入。但是,我要解析的 XML 存储在一个字符串中。有什么方法可以在不将字符串转储到文件中然后再读回的情况下继续进行?
问问题
1412 次
1 回答
3
这是一个示例方法,采用您的模型字符串和解析 xml 并返回 EObject 的 ECorePackage 实例。
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);
}
于 2012-11-18T04:49:25.550 回答