JAXB rename attribute

可紊 提交于 2020-01-14 10:33:23

问题


I have some class with a terrible long name, which is transformed into XML with JAXB. Using @XmlRootElement(name="nicername"), I am able to rename the outer XML tag to <nicername>.

How do I rename individual attributes with ugly names of the class to some nice name too ?


回答1:


You can use the @XmlAttribute and @XmlElement annotations to change the XML names. If you annotate the fields be sure to use the @XmlAccessorType(XmlAccessType.FIELD) annotation on the class:

@XmlRootElement(name="nice-name")
@XmlAccessorType(XmlAccessType.FIELD)
public class UglyName {

    @XmlElement(name="nice-element-name")
    private String uglyElementName;

    @XmlAttribute(name="nice-attribute-name")
    private String uglyAttributeName;

}

Or you can annotate the properties:

@XmlRootElement(name="nice-name")
public class UglyName {

    private String uglyElementName;
    private String uglyAttributeName;

    @XmlElement(name="nice-element-name")
    public String getUglyElementName() {
         return uglyElementName;
    }

    public void setUglyElementName(String name) {
         this.uglyElementNamne = name;
    }

    @XmlAttribute(name="nice-attribute-name")
    public String getUglyAttributeName() {
         return uglyAttributeName;
    }

    public void setUglyAttributeName(String name) {
         this.uglyAttributeNamne = name;
    }

}



回答2:


You can define alternate names for your object properties using:

  • XMLAttribute annotation for attributes
  • XMLElement annotations for elements



回答3:


Both the @XmlAttribute and @XmlElement annotations can be remapped by name using identical syntax as the @XmlRootElement annotation. So, just attach the relevant annotations to each individual field/property you need remapped and provide an argument for "name".



来源:https://stackoverflow.com/questions/15100680/jaxb-rename-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!