[英]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"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.