Search code examples
xmlxsdjaxbschemamarshalling

Generate custom attribute in XML from XSD


I am trying to marshal to xml using JAXB.

My Requirement

if any elements value is null then the xml should have that element's attribute as nullable="true".

I tried putting minoccurs="1", nillable="true" in XSD, but it gave me nil="true" in my xml, but I wanted to show as nullable="true" exactly in my xml.

     <xs:sequence>
     <xs:element name="itemName" type="xs:string" />
     <xs:element name="purchasedOn" type="xs:date" minOccurs="1" nillable="true"/>
     <xs:element name="amount" type="xs:decimal" />
    </xs:sequence>

In my XML :

 <purchasedOn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

Please correct me if I am wrong.


Solution

  • <xs:complexType name="CustomDate">
    <xs:simpleContent>
    <xs:extension base="xs:date">
    <xs:attribute name="nullable" type="xs:string">
    </xs:attribute>
    </xs:extension>
    </xs:simpleContent>
    </xs:complexType>