1

想使用 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();

正确的做法是什么?

4

1 回答 1

0

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"/>
于 2019-03-18T21:11:45.360 回答