Java HTML / XML How to - Set attribute name for JAXB Binding








Question

We would like to know how to set attribute name for JAXB Binding.

Answer

//w w  w.  ja  v  a  2  s  .  c o  m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
class Weird {

  public String myValue;

  @XmlAttribute(name = "NewValue")
  public String svalue;

  public String getValue() {
    return myValue;
  }

  public void setValue(String value) {
    this.myValue = value;
  }

}

public class Main {
  public static void main(String[] args) throws JAXBException {
    Weird w = new Weird();
    w.myValue = "foo";
    w.svalue = "bar";
    JAXBContext context = JAXBContext.newInstance(Weird.class);
    context.createMarshaller().marshal(w, System.out);
  }

}

The code above generates the following result.