想使用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"/>