FROM:http://ganzhi.bokee.com/2968058.html
通常我们使用EMF的方式是让EMF为我们产生stub代码。但有些情况下可能无法预先生成Java代码,而需要直接从XML文件中直接载入模型。使用GenericXMLResourceFactoryImpl能够直接载入XML文档,不管这个文档是否具有Schema。如果XML文档具有Schema,那么GenericXMLResouceFactoryImpl能够根据schema生成Epackage。(载入没有schema的XML文档是在EMF 2.1.0之后加入的)
java 代码
- package ganzhi.test.emf;
- import java.io.File;
- import java.io.IOException;
- import java.util.HashMap;
- import org.eclipse.emf.common.util.TreeIterator;
- 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.XMLResource;
- import org.eclipse.emf.ecore.xmi.impl.GenericXMLResourceFactoryImpl;
- import org.eclipse.emf.ecore.xmi.impl.XMLParserPoolImpl;
- public class LoadNoSchemaXML {
- /**
- *
- * @param args
- *
- */
- public static void main(String[] args) {
- try {
- HashMap options = new HashMap();
- options.put(XMLResource.OPTION_USE_PARSER_POOL,
- new XMLParserPoolImpl());
- options.put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);
- options.put(XMLResource.OPTION_USE_LEXICAL_HANDLER, Boolean.TRUE);
- ResourceSet rs = new ResourceSetImpl();
- Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
- "xml", new GenericXMLResourceFactoryImpl());
- URI fileURI = URI.createFileURI(new File(
- "ganzhi\\test\\emf\\schema\\LibraryNoS.xml")
- .getAbsolutePath());
- Resource resource = rs.createResource(fileURI);
- resource.load(options);
- int i = 0;
- for (TreeIterator ti = resource.getAllContents(); ti.hasNext();) {
- System.out.println(i);
- System.out.println(ti.next());
- i++;
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }