Sanni
Sanni

Reputation: 57

Need to rename XML Element with one of its own properties

I know we can use @XMLRootElement annotation to set the name by which we want this to appear in XML after object to xml conversion using JAXB but I am looking about the way so that XML Elements can be renamed with one of its own properties like for the POJO

class Field
{
    String fieldName;
    String fieldValue;

    //getter/setter
}

after object to xml conversion using JAXB, instead of

<Field>
     <fieldName>FirstName</fieldName>
     <fieldValue>Rahul</fieldValue>
</Field

I need the above xml formatted as

<FirstName>Rahul</FirstName> 

I know I can simply get this if I declare FirstName as String but somehow I need to do as explained above.

Upvotes: 1

Views: 448

Answers (2)

ondrc
ondrc

Reputation: 106

If you are using MOXy/Eclipselink then there is @XmlVariableNode annotation available. You would need to specify it on the object that holds the Field (if Field is the root then I fear @XmlVariableNode won't help). Example:

class Field {
    @XmlTransient
    String fieldName;
    @XmlValue
    String fieldValue;
}

class Holder {
    @XmlVariableNode("fieldName")
    Field field;
}

Note that @XmlVariableNode is a MOXy specific annotation. It appears to be available since 2.6 version.

Upvotes: 1

ninja.coder
ninja.coder

Reputation: 9648

Yes you can set the name of the properties like you want them to appear by annotating them with @JsonProperty(...).

In your can you can do something as follows:

class Field
{
    @JsonProperty("FirstName")
    String fieldName;
    String fieldValue;

    /* Getter-Setters */
}

Upvotes: 0

Related Questions