How to use EMF to read XML file?

zengr picture zengr · Mar 30, 2010 · Viewed 18.2k times · Source

EMF = Eclipse Modeling Framework

I have to use EMF in one of my class projects. I am trying to understand how to use EMF to do the following:

  1. Read XML,
  2. Get the values into objects.
  3. Use ORM to persist the values in objects to database. - Done
  4. Get data from database using ORM and generate XML.

I need to do all of that using: EMF (no idea what so ever) and JPA (DONE).

I have used JAXB and I know, this can be done using JAXB, but how is (EMF == JAXB)?!

I have created many java classes using EMF, but there are so many of them! Where do I implement the read/write methods and how do I run the EMF project?

Thanks

UPDATE1 HINT http://www.eclipsezone.com/eclipse/forums/t58829.html

UPDATE2

I have schema and I have generated the model code using the .xsd. Now I am having problem in reading the data from the XML file.

Answer

Zsolt Török picture Zsolt Török · Feb 7, 2011

You can read arbitrary XML files with EMF, provided you have the XSD for them, and you don't even have to generate Java classes from the XSD.
I blogged about this a couple of months ago, but I will paste the code snippets here as well. For a slightly more detailed explanation see my blog post on How to load and compare arbitrary XML files with EMF.

First you need to load the XSD and initialize a couple of things:

// generate EPackages from schemas
XSDEcoreBuilder xsdEcoreBuilder = new XSDEcoreBuilder();
Collection generatedPackages = xsdEcoreBuilder.generate(schemaURI);

// register the packages loaded from XSD
for (EObject generatedEObject : generatedPackages) {
    if (generatedEObject instanceof EPackage) {
        EPackage generatedPackage = (EPackage) generatedEObject;
        EPackage.Registry.INSTANCE.put(generatedPackage.getNsURI(),
            generatedPackage);
    }
}

// add file extension to registry
ResourceFactoryRegistryImpl.INSTANCE.getExtensionToFactoryMap()
    .put(MY_FILE_EXTENSION, new GenericXMLResourceFactoryImpl());

After that you can load your XML files like you would normally do:

ResourceSet resourceSet = ResourceSetFactory.createResourceSet();
Resource resource = resourceSet.getResource(xmlURI, true);
resource.load(Collections.EMPTY_MAP);
EObject root = resource.getContents().get(0);