Search code examples
javaxmlsoapjaxbmoxy

In JAXB, How can I set node value to attribute value for a string field?


I need to send this certain type of xml message to a web service;

<Personel>
    <name value="HelpMe"/>
    <surname value="Please"/>
</Personel>

My code is like;

@XmlRootElement(name = "Personel")
@XmlAccessorType(XmlAccessType.FIELD)
public class Personel{

    @XmlElement(name = "name")
    String name;

    @XmlElement(name = "surname")
    String surname;
}

But this code produces xml like;

<Personel>
    <name>HelpMe<name/>
    <surname>Please<surname/>
</Personel>

I couldn't find a proper way to do this without create name and surname classes with attribute fields named "value".


Solution

  • I've found moxy implementation of jaxb as a solution. It gives the capability giving default attribute keys.

    Answer about using moxy as default jaxb implementation : Use Moxy as default JAXB Implementation

    @XmlRootElement(name = "Personel")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Personel{
    
        @XmlPath("name/@value")
        String name;
    
        @XmlPath("surname/@value")
        String surname;
    }
    

    So above code generates the following xml as I desired,

    <Personel>
        <name value="HelpMe"/>
        <surname value="Please"/>
    </Personel>