使用 EMF 以字符串格式解析 XML [英] Parse XML in string format using EMF

查看:31
本文介绍了使用 EMF 以字符串格式解析 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

这是一个示例方法,它接收您的 modelString 和解析 xml 并返回 EObject 的 ECorePackage 实例.

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);
}

这篇关于使用 EMF 以字符串格式解析 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆