你可以这样做:
Java 模型
布莱斯道恩
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="blaise-doughan")
public class BlaiseDoughan {
}
我的根
然后每个对它的引用都可以用@XmlElementRef
.
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyRoot {
@XmlElementRef
private BlaiseDoughan blaiseDoughan;
public void setBlaiseDoughan(BlaiseDoughan blaiseDoughan) {
this.blaiseDoughan = blaiseDoughan;
}
}
演示代码
演示
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyRoot.class);
MyRoot myRoot = new MyRoot();
myRoot.setBlaiseDoughan(new BlaiseDoughan());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(myRoot, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8"?>
<myRoot>
<blaise-doughan/>
</myRoot>
为什么这样有效
@XmlElementRef
对应ref
于元素定义中的使用:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="blaiseDoughan"/>
<xsd:complexType name="myRoot">
<xsd:sequence>
<xsd:element ref="blaise-doughan"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="myRoot" type="myRoot"/>
<xsd:element name="blaise-doughan" type="blaiseDoughan"/>
</xsd:schema>