Search code examples
javaxmljaxbmoxy

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.


Solution

  • 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.