You can read arbitrary XML files with EMF, provided you have the XSD for them, and you don't even have to generate Java classes from the XSD.
I blogged about this a couple of months ago, but I will paste the code snippets here as well. For a slightly more detailed explanation see my blog post on How to load and compare arbitrary XML files with EMF.
First you need to load the XSD and initialize a couple of things:
// generate EPackages from schemas
XSDEcoreBuilder xsdEcoreBuilder = new XSDEcoreBuilder();
Collection generatedPackages = xsdEcoreBuilder.generate(schemaURI);
// register the packages loaded from XSD
for (EObject generatedEObject : generatedPackages) {
if (generatedEObject instanceof EPackage) {
EPackage generatedPackage = (EPackage) generatedEObject;
EPackage.Registry.INSTANCE.put(generatedPackage.getNsURI(),
generatedPackage);
}
}
// add file extension to registry
ResourceFactoryRegistryImpl.INSTANCE.getExtensionToFactoryMap()
.put(MY_FILE_EXTENSION, new GenericXMLResourceFactoryImpl());
After that you can load your XML files like you would normally do:
ResourceSet resourceSet = ResourceSetFactory.createResourceSet();
Resource resource = resourceSet.getResource(xmlURI, true);
resource.load(Collections.EMPTY_MAP);
EObject root = resource.getContents().get(0);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…