简体   繁体   中英

Adding attribute to xml element within JAXB API

I am using JAXB API for mapping a Java object to XML. My Java class is

@XmlRootElement(name = "ad")
@XmlAccessorType(XmlAccessType.FIELD)
class Item {

    @XmlElement(name = "id", nillable = false)
    @XmlCDATA
    private int id;

    @XmlElement(name = "url", nillable = false)
    @XmlCDATA
    private String url;


    public Item() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

Output is like this :

<ad>
    <id><![CDATA[ 104 ]]></id>
    <url><![CDATA[www.google.com]]></url>
</ad>

I need to add an attribute to url element, for example :

 <ad>
        <id><![CDATA[ 104 ]]></id>
        <url type="fr"><![CDATA[www.google.fr]]></url>
    </ad>

I have tried many combinaisons using @XmlValue and @XmlAttribute ...

Your url variable should not be a String, but should be its own type. You should create a separate class for the url item, Url, and give it a String field, type, with an @XmlAttribute annotation.

For example,

@XmlRootElement(name = "ad")
@XmlAccessorType(XmlAccessType.FIELD)
class Item {
   @XmlElement(name = "id")
   private int id;
   @XmlElement(name = "url")
   private Url url;

   public Item() {
   }

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   // @XmlAttribute
   public Url getUrl() {
      return url;
   }

   public void setUrl(Url url) {
      this.url = url;
   }
}

@XmlRootElement(name = "url")
@XmlAccessorType(XmlAccessType.FIELD)
class Url {
   @XmlValue
   private String value;
   @XmlAttribute(name = "type")
   private String type;

   public String getValue() {
      return value;
   }

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

   public String getType() {
      return type;
   }

   public void setType(String type) {
      this.type = type;
   }
}

Note that I don't have MOXY so I can't use or test your @XmlCDATA annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM