Save and load an EMF model to an XML file

Here are two code snippets which give you an example how to save and load an EMF model to an XML file.

Note that “Data” is my EMF model object.

Save EMF to XML file:

  1. public void saveData(String fileName, Data data) throws IOException {  
  2.   Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
  3.   Map<String, Object> m = reg.getExtensionToFactoryMap();
  4.   m.put("daform", new XMIResourceFactoryImpl());
  5.  
  6.   ResourceSet resSet = new ResourceSetImpl();
  7.   Resource resource = resSet.createResource(URI.createFileURI(fileName));
  8.   resource.getContents().add(data);
  9.   resource.save(Collections.EMPTY_MAP);
  10. }

Load to EMF object:

  1. public Data loadData(String fileName) throws FileNotFoundException, IOException {
  2.   XMIResourceImpl resource = new XMIResourceImpl();
  3.   File source = new File(fileName);
  4.   resource.load( new FileInputStream(source), new HashMap<Object,Object>());
  5.   Data data = (Data)resource.getContents().get(0);  
  6.   return data;
  7. }
This entry was posted in Eclipse, Java and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>