Generating Dynamic Ecore from XML Schema
As mentioned previously, if your model is an XML Schema but you choose not to generate Java classes, you can dynamically create an Ecore model using the XSDEcoreBuilder. This example uses ipo.xsd
XSDEcoreBuilder xsdEcoreBuilder = new XSDEcoreBuilder();
ResourceSet resourceSet = new ResourceSetImpl();
Collection eCorePackages =
The generate method returns Ecore packages that are created for each URI in this schema. If the schema imports other namespaces, more than one Ecore package is returned. Each package is registered locally in the resource set used to convert schema. Therefore, if you use the same resource set to load your instance XML document, you don't need to register the packages yourself.
Because XML Schema includes more concepts than Ecore, for example wildcards, EMF uses Ecore EAnnotations to record the mapping to XML Schema. During (de) serialization of the data EMF needs to process these annotations. To ensure these annotations are respected during (de) serialization, you must use the XMLResource.ExtendedMetaData option:
HashMap options = new HashMap();
// refer http://www.w3.org/TR/2004/PER-xmlschema-0-20040318/#ipo.xml
Resource resource = resourceSet.createResource(URI.createFileURI("c:/temp/ipo.xml"));
EMF 2.1 also adds a new capability that allows you to convert schemas to Ecore on the fly while loading an XML document that contains an xsi:schemaLocation
attribute. It also allows you to load an XML document that has no schema associated with it. To use this functionality you need to register org.eclipse.emf.ecore.xmi.impl.GenericXMLResourceFactoryImpl
This article gave you a short introduction to EMF, explaining the core EMF concepts, and provided useful examples on how to exploit the dynamic capabilities of EMF.
| Note: The opinions expressed in this paper are those of the authors, not of the IBM Corporation. IBM, alphaWorks, developerWorks, and WebSphere are trademarks of International Business Machines Corporation in the United States, other countries, or both. Rational is a registered trademark of International Business Machines Corporation and Rational Software Corporation, in the United States, other countries or both. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Other company, product and service names may be trademarks or service marks of others.