1

I am using JAXB to create the xml using java Objects.

I am trying to create this tag:

<preTaxAmount currency="USD">84</preTaxAmount>

For this I am using following domain class:

public class PreTaxAmount
{
  @XmlElement(required = false, nillable = true, name = "content")
  private String content;
  @XmlElement(required = false, nillable = true, name = "currency")
  private String currency;

  public String getContent ()
  {
      return content;
  }

  public void setContent (String content)
  {
      this.content = content;
  }

  public String getCurrency ()
  {
      return currency;
  }

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

The above code is producing the following xml:

<preTaxAmount> <content>380.0</content> <currency>USD</currency> </preTaxAmount>

This format is way to different than required one. How to get the desired format.

Ram Dutt Shukla
  • 1,351
  • 7
  • 28
  • 55

2 Answers2

1

You need to use @XmlAttribute annotation for the currency. Similar question here.

Community
  • 1
  • 1
Guillotine1789
  • 342
  • 4
  • 12
0

The following class gives the required xmls tag <preTaxAmount currency="USD">84</preTaxAmount>

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;

@XmlAccessorType(XmlAccessType.FIELD)
public class PreTaxAmount implements Serializable
{
  private static final long serialVersionUID = 1L;

  @XmlAttribute
  private String currency;

  @XmlValue
  protected Double preTaxAmount;

  /**
   * @return the currency
   */
  public String getCurrency()
  {
    return currency;
  }

  /**
   * @param currency
   *          the currency to set
   */
  public void setCurrency(String currency)
  {
    this.currency = currency;
  }

  /**
   * @return the preTaxAmount
   */
  public Double getPreTaxAmount()
  {
    return preTaxAmount;
  }

  /**
   * @param preTaxAmount
   *          the preTaxAmount to set
   */
  public void setPreTaxAmount(Double preTaxAmount)
  {
    this.preTaxAmount = preTaxAmount;
  }

}

When I set the values like this:

  PreTaxAmount preTaxAmount = new PreTaxAmount();
  preTaxAmount.setCurrency("USD");
  preTaxAmount.setPreTaxAmount(84.0);
  orderItem.setPreTaxAmount(preTaxAmount);
Ram Dutt Shukla
  • 1,351
  • 7
  • 28
  • 55