Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a class has @XmlElement property, it cannot have @XmlValue property

Tags:

java

xml

jaxb

I get the following error:

If a class has @XmlElement property, it cannot have @XmlValue property

updated class:

    @XmlType(propOrder={"currencyCode", "amount"})
    @XmlRootElement(name="priceInclVat")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class PriceInclVatInfo {

    @XmlAttribute
    private String currency;
    @XmlValue
    private String currencyCode;
    private double amount;

    public PriceInclVatInfo() {}

    public PriceInclVatInfo(String currency, String currencyCode, double amount) {
        this.currency = currency;
        this.currencyCode = currencyCode;
        this.amount = amount;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public String getCurrencyCode() {
        return currencyCode;
    }

    public void setCurrencyCode(String currencyCode) {
        this.currencyCode = currencyCode;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

}

I want to achive the following output, with an element attribute and value:

<currencyCode plaintext="£">GBP</currencyCode>

How can I achieve this? Is it possible if I have @XmlRootElement(name="priceInclVat")?

like image 892
Martin Avatar asked Sep 23 '14 14:09

Martin


1 Answers

For the error:

If a class has @XmlElement property, it cannot have @XmlValue property

Since you have specified field access, by default the unannotated amount field is treated as having @XmlElement.

private double amount;

You can do one of the following:

  1. Annotate amount with @XmlAttribute
  2. Annotate amount with @XmlTransient.
  3. Change@XmlAccessorType(XmlAccessType.FIELD) to @XmlAccessorType(XmlAccessType.NONE) so that only annotated fields are treated as mapped.

How can I achieve this? Is it possible if I have @XmlRootElement(name="priceInclVat")?

You can wrap the instance of PriceInclVatInfo in an instance of JAXBElement to override the root element and marshal that.

like image 72
bdoughan Avatar answered Oct 16 '22 20:10

bdoughan