Thursday, 26 November 2015

Understanding XSD with real hands on


Design the XSD :

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.service.quiz.gps.com/model"
xmlns:tns="http://www.service.quiz.gps.com/model" elementFormDefault="qualified">

<element name="users" type="tns:UserVO"/>

<complexType name="UserVO">
         <sequence>
      <element  name="id" type="int" maxOccurs="1"  minOccurs="1"/>                           <element  name="user_id" type="long" maxOccurs="1"  minOccurs="1"/>
        <element  name="lastActive" type="date" maxOccurs="1"  minOccurs="0"/>
        <element  name="name" type="string" maxOccurs="1"  minOccurs="1"/>
        <element  name="photo" type="base64Binary" maxOccurs="1"  minOccurs="0"/>
        <element  name="comment" type="string" maxOccurs="1"  minOccurs="0"/>
        <element  name="lastUpdated" type="date" maxOccurs="1"  minOccurs="0"/>
        </sequence>
</complexType>
</schema>

in above XSD yellow highlighted color element is known as global element


Step-2
XML Instance document as per above XSD


<?xml version="1.0" encoding="UTF-8"?>
<users xmlns="http://www.service.quiz.gps.com/model"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.service.quiz.gps.com/model usersLogin.xsd ">
<id>2000</id>
<user_id>983737373</user_id>
<lastActive>2002-09-24-06:30</lastActive>
<name>Nilay</name>
<comment>We are learning concept of XSD</comment>
<lastUpdated>2015-09-24-06:30</lastUpdated>

</users>

Step-3

usersLogin.xjb

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
               jaxb:version="2.0">
 <jaxb:globalBindings>
          <jaxb:javaType   name="java.sql.Timestamp"
        xmlType="xsd:date"
        parseMethod="lol.XsdDateTimeConverter.unmarshal"
        printMethod="lol.XsdDateTimeConverter.marshalDateTime"        
          />
    </jaxb:globalBindings>   

</jaxb:bindings>

above file is basically used for conversion of data types of XSD and into
java data types

D:\>xjc -b foo.xjb userLogin.xsd

D:\>xjc -b foo.xjb -extension usersLogin.xsd


Implementing Serializable interface for all the generated classes

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" jaxb:version="2.1">

 <jaxb:globalBindings>

         <jaxb:javaType   name="java.sql.Timestamp"
        xmlType="xsd:date"
        parseMethod="lol.XsdDateTimeConverter.unmarshal"
        printMethod="lol.XsdDateTimeConverter.marshalDateTime"        
 />
<xjc:serializable uid="1" />
         </jaxb:globalBindings>   

</jaxb:bindings>


 This will also work..................................
<jaxb:serializable uid="1" />