Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

java - How to use EMF to read XML file?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...