Himanshu Yadav
Himanshu Yadav

Reputation: 13585

JAXB: Unmarshal and set a part of attribute value

I am getting a long string as attribute and I want to unmarshal a part of it.
Here is what element look like:

<Party id="PARTYID_1341592540748_ed044bd3-b8b2-40f9-a679-4daa411ecc45">

But I want just 1341592540748 to be set as id.
Is it possible to edit @XmlAttribute string on the fly ?

Upvotes: 1

Views: 440

Answers (2)

bdoughan
bdoughan

Reputation: 149047

I would recommend implementing an instance of XmlAdapter to contain this logic. The advantage of this approach is that the XML conversion logic is kept separate from your domain model. An XmlAdapter is set on a field/property using the @XmlJavaTypeAdapter annotation.

For More Information

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122414

One approach might be to do the conversion in a setter method, something like this (not tested):

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Party {

  @XmlTransient long id;

  // traditional JavaBean accessors for the long, _not_ used by JAXB
  public long getId() { return id; }
  public void setId(long id) { this.id = id; }

  // converting accessors for JAXB
  @XmlAttribute(name = "id")
  public String getStringId() { return String.valueOf(id); }
  public void setStringId(String idStr) {
    // extract relevant bit of the string and parse it into a long
  }
}

Upvotes: 1

Related Questions