Jaxb marshaller always writes xsi:nil (even when @XmlElement(required=false, nillable=true))

后端 未结 1 1031
难免孤独
难免孤独 2020-12-17 17:53

I have a java property annotated with @XmlElement(required=false, nillable=true). When the object is marshalled to xml, it is always outputted with the xs

相关标签:
1条回答
  • 2020-12-17 18:50

    If the property is annotated with @XmlElement(required=false, nillable=true) and the value is null it will be written out with xsi:nil="true".

    If you annotate it with just @XmlElement you will get the behaviour you are looking for.

    import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;

    Example

    Given the following class:

    @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;
    
    }
    

    And this demo code:

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

    The result will be:

    <?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>
    
    0 讨论(0)
提交回复
热议问题