Tuesday, March 22, 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”); 

5 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
  4. Hi Kinshuk

    I am trying to generate xsd from a View Object with the above code but getting com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 10 counts of IllegalAnnotationsExceptions
    oracle.jbo.Row is an interface, and JAXB can't handle interfaces....

    Can you pls. help me on this

    Thanks,
    MC

    ReplyDelete
  5. Hi Kinshuk

    I am trying to generate xsd from a View Object with the above code but getting com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 10 counts of IllegalAnnotationsExceptions
    oracle.jbo.Row is an interface, and JAXB can't handle interfaces....

    Can you pls. help me on this

    Thanks,
    Madhu

    ReplyDelete

Chitika