1

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 ...

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.