Jaxb marshaller scrive sempre xsi: nil (anche quando @xmlelement (richiesto = false, nillable = true))

StackOverflow https://stackoverflow.com/questions/5897785

  •  29-10-2019
  •  | 
  •  

Domanda

Ho una proprietà Java annotata con @XmlElement(required=false, nillable=true). Quando l'oggetto viene maturato a XML, viene sempre emesso con il xsi:nil="true" attributo.

Esiste un'opzione JaxbContext/Marshaller per indirizzare il Marshaller a non scrivere l'elemento, piuttosto che scriverlo con xsi:nil?

Ho cercato risposte a questo e ho anche dato un'occhiata al codice, afaics, scriverà sempre xsi:nil Se nillable = true. Mi sto perdendo qualcosa?

È stato utile?

Soluzione

Se la proprietà è annotata con @XmlElement(required=false, nillable=true) e il valore è nullo con cui verrà scritto xsi:nil="true".

Se lo annoti con solo @XmlElement Otterrai il comportamento che stai cercando.

import javax.xml.bind.annotation.xmlaccesstype; import javax.xml.bind.annotation.xmlaccessorType; import javax.xml.bind.annotation.xmlelement; import javax.xml.bind.annotation.xmlrootelement;

Esempio

Data la seguente classe:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement(nillable=true, required=true)
    private String elementNillableRequired;

    @XmlElement(nillable=true)
    private String elementNillbable;

    @XmlElement(required=true)
    private String elementRequired;

    @XmlElement
    private String element;

}

E questo codice demo:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Root root = new Root();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        marshaller.marshal(root, System.out);
    }

}

Il risultato sarà:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <elementNillableRequired xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    <elementNillbable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</root>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top