How to instantiate an empty element with JAXB

前端 未结 4 1478
-上瘾入骨i
-上瘾入骨i 2020-12-10 04:30

I use JAXB to create XML messages. The XML I need to create is (for the sake of simplicity):


  
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 04:57

    As @Tom Hawtin - tackline said

    and
    is same. Parsers will give you "".

    You have to to put nillable on your header annotation

    @XmlElement(nillable=true, required=true)
    public String getHeader() {
      return header;
    }
    

    I hope this code will generate following XML for null value.

    import javax.xml.bind.*;
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    public class Request {
    
        public static void main(String[] args) throws JAXBException {
            final Request request = new Request();
            final JAXBContext context = JAXBContext.newInstance(Request.class);
            final Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                                   Boolean.TRUE);
            marshaller.marshal(request, System.out);
            System.out.flush();
        }
    
        @XmlElement(nillable=true, required=true)
        private String header;
    }
    

    prints

    
    
        

提交回复
热议问题