2011年10月6日 星期四

使用EMF來Serialize XML

EMF提供了將定義好的metamodel serialize成XMI(XML Interchange)格式的功能。使用這個功能,可以將Object 序列化為XMI文檔。程式如下:(此範例程式使用了由My.ecore這個EMF meta model產生出來的model code。此處可下載emftest.zip(內含My.ecore),下載後需再用EMF的工具,產生EMFTest這些package的Java code)

import EMFTest.EMFTestFactory;
  import EMFTest.EMFTestPackage;
  import EMFTest.vincent;
  import EMFTest.impl.EMFTestPackageImpl;

public class TestData {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //要先Initial PackageImpl,才能使用EMF的功能
        EMFTestPackageImpl.init();
        //Serialize時,所需的參數儲存於 saveOptions
        Map<String, Object> saveOptions = new HashMap<String, Object>();
        //啟用OPTION_EXTENDED_META_DATA後,才能指定要讓某個attribute Serialize為Element,而不是Attributes
        saveOptions.put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);
        //設定vincent.company及vincent.location這2個attribute要serialize成Element
        EMFTestPackage testPackage = EMFTestPackageImpl.eINSTANCE;
        EAttribute companyAttr = testPackage.getvincent_Company();
        EAttribute locationAttr = testPackage.getvincent_Location();
        XMLMapImpl map = new XMLMapImpl();
        XMLInfoImpl x = new XMLInfoImpl();
        x.setXMLRepresentation(XMLInfoImpl.ELEMENT);
        map.add(companyAttr, x);
        map.add(locationAttr, x);
        saveOptions.put(XMLResource.OPTION_XML_MAP, map); 
        saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8");      

     EMFTestFactory testFactory = EMFTestFactory.eINSTANCE;
        vincent testElement = testFactory.createvincent();
        testElement.setAge(32);
        testElement.setCompany("IBM");
        testElement.setLocation("Taipei");
        ResourceSet resourceSet = new ResourceSetImpl();
        // Register XML resource factory
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xml", new XMLResourceFactoryImpl());
        Resource resource = resourceSet.createResource(URI.createFileURI("Vincent.xml"));
        // add the root object to the resource
        resource.getContents().add(testElement);
        // serialize resource – you can specify also serialization
        // options which defined on org.eclipse.emf.ecore.xmi.XMIResource
        try {
            resource.save(saveOptions);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

上面的程式中,透過啟用OPTION_EXTENDED_META_DATA,使得可以設定那些EMF model的attribute要產生成XML的element。另一種做法為,直接在Ecore model的diagram中,增加Extended Meta Data,把要設定的Attribute設為element。如下圖

注意:這個方法要work,一樣要在serialize XML的程式中,加入

saveOptions.put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);

image

參考資料:

沒有留言:

張貼留言