import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.common.util.URI;
import yxy.Bag;
import yxy.YxyFactory;
import yxy.YxyPackage;
public class DriverWrite {
public static void main(String[] args) {
YxyPackage.eINSTANCE.eClass();
Bag bag_caoch = YxyFactory.eINSTANCE.createBag();
bag_caoch.setBrand("Caoch");
Bag bag_mk = YxyFactory.eINSTANCE.createBag();
bag_mk.setBrand("Michael Kors");
// 注册XML扩展
Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("xml", new XMIResourceFactoryImpl());
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.createResource(URI.createURI("My2.xml"));
System.out.println(resource);
resource.getContents().add(bag_caoch);
resource.getContents().add(bag_mk);
try {
resource.save(Collections.EMPTY_MAP);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My2.xml就会生成在项目的目录下
import java.util.Map;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import yxy.Bag;
import yxy.YxyPackage;
public class DriverRead {
public static void main(String[] args) {
// TODO Auto-generated method stub
YxyPackage.eINSTANCE.eClass();
// 注册XML扩展
Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("xml", new XMIResourceFactoryImpl());
// 创建一个资源
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.getResource(URI.createURI("My2.xml"), true);
Bag bag_caoch = (Bag) resource.getContents().get(0);
Bag bag_mk = (Bag) resource.getContents().get(1);
System.out.println(bag_caoch.getBrand());
System.out.println(bag_mk.getBrand());
}
}
<?xml version="1.0" encoding="ASCII"?>
<xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:yxy="http://yxy.csz.com">
<yxy:Bag brand="Caoch"/>
<yxy:Bag brand="Michael Kors"/>
</xmi:XMI>