How to remove not required Elements from generated

2019-07-19 06:09发布

问题:

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

回答1:

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.