如何在全局范围内更改特定类型的元素名称?

时间:2013-08-22 18:51:02

标签: jaxb jaxb2

假设有一个名为

的类
// 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技术吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

Java模型

<强> 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>