Monday, 21 March 2011

Create XSD file with JAXB

I have explained, generating java classes from xsd. But now it reverse. Then we did xml serialization. But how to generate xsd?

In order to do this, add to your Java project (described in previous 2 articles) the following method:

public void generateSchema(String suggestedSchemaName) throws Exception
{
final File parentFolder = new File(".");
final String schemaName = suggestedSchemaName;

JAXBContext jc = JAXBContext.newInstance(Graph.class);
jc.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespace, String schema) throws IOException {
return new StreamResult(new File(parentFolder, schemaName));
}
});
}


As you can see, JAXBContext class has the generateSchema method, which takes an instance of a SchemaOutputResolver class, that needs to override the createOutput method in order to output the XSD file. So you can afterwards call the method presented above as follow:

generateSchema(“graphXmlSchema.xsd”); 

3 comments:

  1. This is good. Bur how I can change type for a particular variable? Like for a variable xyz I want to restrct with values XX, YY?

    ReplyDelete
  2. Hi Pradeep, you can do it by using Enum offcourse. Suppose you are writing size, and it is XS, XL and XXL.
    In the xsd just do following :













    I hope it helps you :)

    ReplyDelete
  3. Hi Pradeep, you can do it by using Enum offcourse. Suppose you are writing size, and it is XS, XL and XXL.
    In the xsd just do following :
    <xs:simpleType name="SizeType">
    <xs:union memberTypes="DressSizeType">
    <xs:simpleType>
    <xs:restriction base="xs:token">
    <xs:enumeration value="XS"/>
    <xs:enumeration value="XL"/>
    <xs:enumeration value="XXL"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:union>
    </xs:simpleType>




    I hope it helps you :)
    (XML was not visible in last comment)

    ReplyDelete