EMF - Convert XML model to XMI

3.1k Views Asked by At

I have created an .ecore and .genmodel metamodel from an .xsd file. I'am trying to create a model instance from an .xml file conforming to .xsd file (and in consequence to .ecore metamodel). How can I achieve this goal?

2

There are 2 best solutions below

0
On BEST ANSWER

At the end I just need to change root node name. To achieve this goal you just need to follow the next steps:

  1. At your ecore diagram right click your root node (the equivalent of your root node in your xml file).
  2. Click on create dynamic instance.
  3. Make a test model. This model is an XMI instance.
  4. At the end you just have to change your rood node information for the new one (the one generated in the XMI model).

In my case I replaced

/* At XML file */

<featureModel>
//Here you find the model nodes
...
</ featureModel>

With

/* XML file converted to XMI file. This file conforms to XSD and ecore model. */

<ide:FeatureModelType [here you will find some attributes]>
//Here you find the model nodes just as they where defined earlier
...
</ide:FeatureModelType>

Of course this could be made programmatically.

1
On

Only you have to load your XML file in a EMF resource, setting the load option XMLResource.OPTION_SUPPRESS_DOCUMENT_ROOT as true. After that you have to create an output resource setting the URI as your file .xmi. Finally you get your root element from the XML model resource and insert it in your XMI model resource, after that you save your output model and it is done.

Resource loadResource = new ResourceImpl(sourceURI); //We create a resource with XML file uri as parameter, to load de XML model.

// Set option to load configuration file
Map options = new HashMap(); 
// The option below deleted Document root in output file
options.put(XMLResource.OPTION_SUPPRESS_DOCUMENT_ROOT, true);
loadResource.load(options); // Now we have load the XML model

// Create an output resource where copy element from input resource
Resource resourceOut = new Resource(targetURI); //We create a resource to XMI file

// Copying elements from input resource to output resource
EList<EObject> listObj = loadResource.getContents();
EObject obj = listObj.get(0);
resourceOut.getContents().add(obj);

resourceOut.save() //We serialize the resource to the XMI file