想使用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();
正确的做法是什么?
答案 0 :(得分:0)
如果要将ElementName
设置为value
的{{1}}实现此目标,请删除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;
}