Take the 2-minute tour ×

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">
                        A name given to the digital record.
                    <xsd:restriction base="xsd:string">
                        <xsd:minLength value="1"></xsd:minLength>

As you can see it is not a mandatory element because


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


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


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();
             * Validate Against Schema.
             * Marshal will throw an exception if XML not validated against
             * schema.
            marshaller.marshal(e, System.out);
share|improve this question
Post your tried source code here. –  The Ranger Sep 3 '12 at 8:40
@THANGA I have updated the question. –  Dangling Piyush Sep 3 '12 at 8:50

1 Answer 1

up vote 2 down vote accepted

If you set the title value to the empty string "" it'll generate <Title/>, if you set it to null it should omit the element entirely.

share|improve this answer
Is there a way to make JAXB generate <Title></Title> for empty string? Looks like few parsers are not treating it exactly same as <Title/> . –  Teddy Aug 21 at 9:23
@Teddy not that I'm aware of, and since those two forms are identical XML that's a bug in the "few parsers" rather than a problem in JAXB. It may be possible to work around if you marshal to an XMLStreamWriter and use a StAX implementation that offers this as a configuration option. I know Woodstox has some options that might cover this if JAXB makes separate start/end tag calls to the writer rather than calling writeEmptyElement, you'll have to experiment with it yourself and see what works. –  Ian Roberts Aug 21 at 10:19

Your Answer


