yang
yang

Reputation: 183

How to use JAXB to add a custom "type" attribute to my XML?

this is a jaxb problem one bean class

  @XmlAccessorType(XmlAccessType.FIELD)
  @XmlType(name = "tableBean") 
  public class TableBean {
  @XmlAttribute
  private String type;

  @XmlElement(name = "created_at")
  private Date created_at;

  @XmlElement(name = "database_id")
  private int database_id;

  @XmlElement(name = "id")
  private int id;

i want xml like this

<tables>
  <table>
     <created_at type="datetime">2013-08-28T21:14:35+09:00</created_at>
     <database_id type="integer">1</database_id>
     <id type="integer">1</id>
 <table>
<tables>

i have try to make a class like this

public class Type_Int {

private String type;
private int id;
@XmlAttribute
public String getType() {
    return type;
}
public void setType(String type) {
    this.type = type;
}
@XmlValue
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

use@XmlAttribute in Type_Int.class i can get i want,but my project have many Variables,i could write classes for everyone,so wheather i can do somthing in my main bean.class,and i can make it easily

Upvotes: 1

Views: 1282

Answers (1)

bdoughan
bdoughan

Reputation: 149047

If you want to map a field like:

private int id;

To an XML element like the following:

<id type="integer">123</id>

Then you could leverage an XmlAdapter. Leveraging the Type_Int class from your question you could do create a class with the following declaration and then implement the required marshal and unmarshal methods to convert Integer to/from Type_Int.

public class IntAdapter extends XmlAdapter<Type_Int, Integer> {
    ...
}

To leverage this adapter you will need to change your field from the primitive type int to the object type Integer and annotate it as:

@XmlJavaTypeAdapter(IntAdapter.class)
private Integer id;

Upvotes: 1

Related Questions