eclipse emf 读写xml文件

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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值