假设有一个名为
的类// with respect.
public class BlaiseDoughan {
}
我知道我可以像这样更改元素的名称。
@XmlRootElement
public class MyRoot {
@XmlElement(name = "blaise-doughan") // I want this
private BlaiseDoughan blaiseDoughan
}
有没有办法在没有BlaiseDoughan
属性的情况下,将blaise-doughan
的目标元素名称永久设置为name
到<{1}}?
我的意思是
@XmlRootElement
public class SomeOtherRoot {
@XmlElement // without the [name = "blaise-doughan"] part?
private BlaiseDoughan blaiseDoughan
}
这有什么package-level
技术吗?
答案 0 :(得分:1)
你可以这样做:
<强> BlaiseDoughan 强>
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="blaise-doughan")
public class BlaiseDoughan {
}
<强> MyRoot 强>
然后,每个对它的引用都可以用@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>