Я использую JAXB для создания xml с использованием java-объектов.
Я пытаюсь создать этот тег:
<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>
Этот формат отличается от требуемого. Как получить желаемый формат.
Вам нужно использовать аннотацию @XmlAttribute
для валюты. Аналогичный вопрос здесь.
Следующий класс дает требуемый тег 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);