繁体   English   中英

Xtext:将模型导出为XMI / XML

[英]Xtext: Export model as XMI/XML

我已经用Xtext定义了DSL。 假设它看起来像这样:

Model:
    components+=Component*
;

Component:
    House | Car
;

House:
    'House' name=ID
    ('height' hubRadius=DOUBLE)? &
    ('width' hubRadius=DOUBLE)?
    'end' 'House'
;

Car:
    'Car' name=ID
    ('maxSpeed' hubRadius=INT)? &
    ('brand' hubRadius=STRING)?
    'end' 'Car'
;

在基于我的DSL的生成的Eclipse IDE中,我实现了一个模型。 假设它看起来像下面的样子:

House MyHouse
    height 102.5
    width 30.56
end House

Car MyCar
    maxSpeed 190
    brand "mercedes"
end Car

我现在想将该模型导出为XMI或XML文件。

我要执行此操作的原因是,我有另一个工作流程,该工作流程允许我使用XMI / XML文件即时更改模型参数。 因此,除了重新定义模型外,我还可以将XML / XMI文件传递给工作流程,该流程会自动执行。

简短示例:DSL允许定义组件HouseCar House允许参数widthheightCar允许参数maxSpeedbrand (请参见上面的语法)。

因此,在我所说的工作流程中,参数将更改为不同的值。 例如,我正在寻找的生成的XML将如下所示:

<model>
    <component name='House'>
        <param name='height'>102.5</param>
        <param name='width'>30.56</param>
    </component>
    <component name='Car'>
        <param name='maxSpeed'>190</param>
        <param name='brand'>mercedes</param>
    </component>
</model>

如何将模型导出为XMI / XML?

我终于找到了解决方案。 下面的代码按照我在开幕文章中的要求导出* .xmi文件:

private void exportXMI(String absuloteTargetFolderPath) {
    // change MyLanguage with your language name
    Injector injector = new MyLanguageStandaloneSetup()
            .createInjectorAndDoEMFRegistration();
    XtextResourceSet resourceSet = injector
            .getInstance(XtextResourceSet.class);

    // .ext ist the extension of the model file
    String inputURI = "file:///" + absuloteTargetFolderPath + "/MyFile.ext";
    String outputURI = "file:///" + absuloteTargetFolderPath + "/MyFile.xmi";
    URI uri = URI.createURI(inputURI);
    Resource xtextResource = resourceSet.getResource(uri, true);

    EcoreUtil.resolveAll(xtextResource);

    Resource xmiResource = resourceSet
            .createResource(URI.createURI(outputURI));
    xmiResource.getContents().add(xtextResource.getContents().get(0));
    try {
        xmiResource.save(null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

只是对约翰的回答的评论:在Eclipse IDE中,绝不要使用MyLanguageStandaloneSetup,必须通过UI插件的激活器访问注入器的实例:MyLanguageActivator.getInstance()。getInjector(MyLanguageActivator.COM_MYCOMPANY_MYLANGUAGE)。

调用MyLanguageStandaloneSetup.createInjectorAndDoEMFRegistration将创建一个新的Injector实例,该实例不同于Eclipse所使用的实例。 它还可能会破坏EMF注册管理机构的状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM