jaxb:我使用不同的方法,但都不起作用

时间:2015-04-28 06:10:02

标签: web-services jaxb jaxb2

我想输出这样的XML:

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

我尝试了@XmlAttribute@XmlElement(nil=true),应该如何使用jaxb。

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

1 个答案:

答案 0 :(得分:1)

Master.java

REFER

List.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;
    }

}

package-info.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;
    }

}

Main.java

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

输出 - XML

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


    }

}