Search code examples
web-servicesjaxbjaxb2

jaxb: I use different method but all doesn't work


I want to output a XML like this:

<master>
   <list type="array" nil="true">
<master>

I have tried @XmlAttribute and @XmlElement(nil=true), how should do this with jaxb.

<slave-status><connect-retry type="integer" nil="true"/>  
    <created_at type="datetime" nil="true"/>
<slave-status>

Solution

  • Master.java

    import javax.xml.bind.JAXBElement;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "master", propOrder = {
        "list"
    })
    public class Master {
    
        @XmlElement(name = "list")
        protected List list;
    
    
        public List getList() {
            return list;
        }
    
    
        public void setList(List value) {
            this.list = value;
        }
    
    }
    

    List.java

    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.XmlType;
    
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "list")
    public class List {
    
        @XmlAttribute(name = "type")
        protected String type;
    
        @XmlAttribute(name = "nil")
        protected boolean nil;
    
        public boolean isNil() {
            return nil;
        }
    
        public void setNil(boolean nil) {
            this.nil = nil;
        }
    
        public String getType() {
            return type;
        }
    
        public void setType(String value) {
            this.type = value;
        }
    
    }
    

    package-info.java

    @javax.xml.bind.annotation.XmlSchema(namespace = "", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
    package com.ca.exporter.util;
    

    Main.java

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    
    public class Main {
    
        public static void main(String[] args) throws JAXBException {
    
            JAXBContext jc =  JAXBContext.newInstance(Master.class);
    
            Master m = new Master();
    
            List l = new List();
            l.setType("array");
            l.setNil(true);
    
            m.setList(l);
    
            Marshaller mar = jc.createMarshaller();
    
            mar.marshal(m, System.out);
    
    
        }
    
    }
    

    Output - XML

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <master>
        <list type="array" nil="true"/>
    </master>