0

我已经用 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允许参数width和,允许参数和(见上面height的语法)。CarmaxSpeedbrand

因此,在我所说的工作流程中,参数将使用不同的值进行更改。例如,我正在寻找的生成的 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?

4

2 回答 2

1

我终于找到了解决方案。下面的代码导出了一个 *.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();
    }
}
于 2016-03-09T07:56:38.687 回答
1

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

调用 MyLanguageStandaloneSetup.createInjectorAndDoEMFRegistration 将创建一个不同于 Eclipse 使用的 Injector 的新实例。它还可以破坏 EMF 注册表的状态。

于 2016-03-10T00:19:11.657 回答