How to remove unneeded elements from generated XML via jaxb

I want to know if there is anyway to remove unnecessary elements from generated xml using jaxb.I has 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, this is not required because

MinOccurs = "0"

But if it is not empty, the length must be 1.

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

      

During sorting, if I leave the Title field, it throws a SAXException due to the minimum length limitation. So I want to remove all occurrence <Title/>

from the generated XML.Right now I removed the minimum length constraint so it adds the element <Title>

as EMPTY

<Title></Title>

      

But I don't want it to look like it. Any help is appreciated. I am using jaxb 2.0 for Marshalling.

UPDATE:

Below is my variable:

  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);

      

+2


source to share


1 answer


If you set the header value to an empty string ""

, it will generate <Title/>

, if you set it to null

, it should omit the element entirely.



+3


source