【问题标题】:how to create a complex xmls tag using JAXB如何使用 JAXB 创建复杂的 xmls 标记
【发布时间】:2015-05-20 20:42:39
【问题描述】:

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

我正在尝试创建这个标签:

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

为此,我使用以下域类:

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>

这种格式与要求的格式不同。如何获得所需的格式。

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

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

    【讨论】:

    • 我会试试这个@XmlAttribute
    • 参考问题有助于解决问题。谢谢!
    【解决方案2】:

    下面的类给出了所需的 xmls 标签 &lt;preTaxAmount currency="USD"&gt;84&lt;/preTaxAmount&gt;

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      相关资源
      最近更新 更多