How to remove not required Elements from generated XML via jaxb

会有一股神秘感。 提交于 2019-12-11 02:25:16

问题


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.



来源:https://stackoverflow.com/questions/12244479/how-to-remove-not-required-elements-from-generated-xml-via-jaxb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!