如何使用 JAXB 创建复杂的 xmls 标签

how to create a complex xmls tag using JAXB

我正在使用 JAXB 创建 xml 使用 java 对象。

我正在尝试创建此标签:

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

为此,我使用以下域 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;
  }
}

以上代码生成以下内容xml:

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

此格式与要求的格式不同。如何得到想要的格式。

您需要对货币使用 @XmlAttribute 注释。类似问题here.

下面class给出了需要的xmls标签 <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;
  }

}

当我这样设置值时:

  PreTaxAmount preTaxAmount = new PreTaxAmount();
  preTaxAmount.setCurrency("USD");
  preTaxAmount.setPreTaxAmount(84.0);
  orderItem.setPreTaxAmount(preTaxAmount);