如何使用 JAXB 创建没有值的 XmlElement

How to create XmlElement with no value with JAXB

想要使用 JAXB 创建以下 XML 元素,没有值(内容),没有结束元素名称,只是结束“/”:

 <ElementName attribute1="A" attribute2="B"" xsi:type="type" xmlns="some_namespace"/> 

尝试以下

@XmlAccessorType(XmlAccessType.FIELD)                                  

public class ElementName {
@XmlElement(name = "ElementName", nillable = true)
protected String value;
@XmlAttribute(name = "attribute1")
protected String attribute1;
@XmlAttribute(name = "attribute2")
protected String attribute2;
}

如下构造该类型的对象时出现异常

ElementName element = new ElementName();

正确的做法是什么?

如果您想为 ElementName 实现它,将 value 设置为 null,请删除 nillable 属性。如何生成 XML 有效负载的简单示例:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class JaxbApp {

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

        ElementName en = new ElementName();
        en.attribute1 = "A";
        en.attribute2 = "B";
        en.value = null;

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(en, System.out);
    }
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "ElementName")
class ElementName {

    @XmlElement(name = "ElementName")
    protected String value;
    @XmlAttribute(name = "attribute1")
    protected String attribute1;
    @XmlAttribute(name = "attribute2")
    protected String attribute2;
}

打印:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ElementName attribute1="A" attribute2="B"/>