How to remove not required Elements from generated XML via jaxb

Posted by Dangling Piyush on Stack Overflow See other posts from Stack Overflow or by Dangling Piyush
Published on 2012-09-03T08:36:49Z Indexed on 2012/09/03 9:38 UTC
Read the original article Hit count: 264

Filed under:
|
|
|
|

I want to know if there is anyway for removing not required elements from generated xml using jaxb.I have my xsd element definition as follows.

           <xsd:element name="Title" maxOccurs="1" minOccurs="0">
                <xsd:annotation>
                    <xsd:documentation>
                        A name given to the digital record.
                    </xsd:documentation>
                </xsd:annotation>
                <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                        <xsd:minLength value="1"></xsd:minLength>
                    </xsd:restriction>
                </xsd:simpleType>
            </xsd:element>

As you can see it is not a mandatory element because

minOccurs="0"

But if it is not empty the length should be 1.

<xsd:minLength value="1"></xsd:minLength>

At the time of marshalling if I left the Title field blank it is throwing the SAXException because of min-length restriction. So what I want to do is to remove the whole occurrence of <Title/> from generated XML.Right now i have removed the min-length restriction so it is adding the <Title> element as EMPTY

<Title></Title>

But I do not want it like this.Any help is appreciated.I am using jaxb 2.0 for Marshalling.

UPDATE:

Following is my variable definiton :

  private JAXBContext jaxbContext;
    private Unmarshaller unmarshaller;
    private SchemaFactory factory;
    private Schema schema;
    private Marshaller marshaller;

Marshalling code.

            jaxbContext = JAXBContext.newInstance(ERecordType.class);
            marshaller = jaxbContext.createMarshaller();
            factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schema = factory.newSchema((new File(xsdLocation)));
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            ERecordType e = new ERecordType();
            e.setCataloging(rc);
            /**
             * Validate Against Schema.
             */
            marshaller.setSchema(schema);
            /**
             * Marshal will throw an exception if XML not validated against
             * schema.
             */
            marshaller.marshal(e, System.out);

© Stack Overflow or respective owner

Related posts about java

Related posts about Xml