| |
Exercise 5 solution | page 3 of 6 |
//Exercise 5 builds from Exercise 4
Lab4 lab4 = new Lab4();
XSDSchema schema = lab4.createSchema(xsdFile); //Schema from lab4
//Lets get the PurchaseOrderType complex type
XSDComplexTypeDefinition purchaseOrderType = schema.resolveComplexTypeDefinition("PurchaseOrderType");
//Lets get the model group that was created in Exercise 4
XSDModelGroup modelGroup = (XSDModelGroup)((XSDParticle)purchaseOrderType.getContent()).getContent();
/**
* Create a global element with name="note" and type="string"
*/
XSDElementDeclaration noteElement = XSDFactory.eINSTANCE.createXSDElementDeclaration();
//Set the name to "notes"
noteElement.setName("notes");
//Set the type of notes element to string
XSDSimpleTypeDefinition stringType = schema.getSchemaForSchema().
resolveSimpleTypeDefinition(XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001,"string");
noteElement.setTypeDefinition(stringType);
//Add the global element to the root schema
schema.getContents().add(noteElement);
/**
* Create local element with name="state", type="po:USState" and minOccurs="0"
* Local elements have particles as parents
*/
XSDParticle localElementParticle = XSDFactory.eINSTANCE.createXSDParticle();
XSDElementDeclaration stateElement = XSDFactory.eINSTANCE.createXSDElementDeclaration();
localElementParticle.setContent(stateElement);
//Set the name to state
stateElement.setName("state");
//Set the type to USState
stateElement.setTypeDefinition(schema.resolveSimpleTypeDefinition("USState"));
//Set the minOccurs="0"
localElementParticle.setMinOccurs(0);
//Add the new particle to the modelgroup
modelGroup.getContents().add(localElementParticle);
/**
* Create the element reference to the global element note
*/
XSDParticle elementRefParticle = XSDFactory.eINSTANCE.createXSDParticle();
XSDElementDeclaration notesRef = XSDFactory.eINSTANCE.createXSDElementDeclaration();
elementRefParticle.setContent(notesRef);
//Set the element reference to the global element notes
notesRef.setResolvedElementDeclaration(noteElement);
//Add the new particle to the modelgroup
modelGroup.getContents().add(elementRefParticle);
//Save the contents of the resource to the file system.
schema.eResource().save(Collections.EMPTY_MAP);
|