使用EMF以字符串格式解析XML

时间:2012-11-06 11:25:14

标签: java xml eclipse-emf

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

1 个答案:

答案 0 :(得分:3)

这是一个示例方法,接受您的modelString和解析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);
}