且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jaxb XmlAccessType:属性示例

更新时间:2023-11-30 21:28:40

答案是您的示例本身并没有错,但是有一些可能的陷阱.您已将注释放在设置器上,而不是在获取器上.虽然JavaDoc for @XmlAttribute对此没有任何限制,但其他批注(例如@XmlID)专门允许批注者或吸气剂,但不能同时批注.

The answer is that your example is not wrong per se, but there are a few possible pitfalls. You have put the annotation on the setter, not the getter. While the JavaDoc for @XmlAttribute does not state any restrictions on this, other annotations (e.g. @XmlID) specifically allow annotation either the setter or the getter, but not both.

请注意,@ XmlAttribute需要一个属性,而不是一个元素.另外,由于它解析属性,因此它不能是复杂的类型.那么EGroup可能是一个枚举?

Note that @XmlAttribute expects an attribute, not an element. Also, since it parses an attribute, it can't be a complex type. So EGroup could be an enum, perhaps?

我扩展了您的示例并添加了一些断言,它使用最新的Java 6在我的机器上"工作.

I expanded your example and added some asserts, and it works "on my machine", using the latest Java 6.

@XmlRootElement
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.PROPERTY)
public class E {

    private EGroup groupDefinition;

    public EGroup getGroupDefinition () {
        return groupDefinition;
    }
    @XmlAttribute
    public void setGroupDefinition (EGroup g) {
        groupDefinition = g;
    }

    public enum EGroup {
        SOME,
        OTHERS,
        THE_REST
    }

    public static void main(String[] args) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(E.class);

        E eOne = new E();
        eOne.setGroupDefinition(EGroup.SOME);

        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        StringWriter writer = new StringWriter();
        m.marshal(eOne, writer);

        assert writer.toString().equals("<e groupDefinition=\"SOME\"/>");

        E eTwo = (E) jc.createUnmarshaller().unmarshal(new StringReader(writer.toString()));

        assert eOne.getGroupDefinition() == eTwo.getGroupDefinition();
    }
}