用JAXB生成具有名称和xsi:type的列表

时间:2018-10-18 13:46:10

标签: jaxb

我从我的班级生成xml。 我的问题在派生对象列表中。我发现了将xsi:type设置为列表中每个元素的能力,并且发现了将对象类型设置为标签名的单独能力。 但是我需要结合两种能力。

下面的详细信息。

这是我的java类

@XmlRootElement(name="BusinessEntityRef")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BusinessEntityRef", propOrder = { "id" })
@XmlSeeAlso({
        TradeRef.class,
        TransactionRef.class,
})
public class BusinessEntityRef
{
    @XmlAttribute(name = "ID", required=true)
    private String id;

    public String getId() { return id; }
    public BusinessEntityRef setId(String id) 
       { this.id = id; return this; }
}

@XmlRootElement(name="TransactionRef")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TransactionRef", propOrder = {  })
public class TransactionRef extends BusinessEntityRef  {
}

@XmlRootElement(name="TradeRef")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TradeRef", propOrder = { "version" })
public class TradeRef  extends BusinessEntityRef {

    @XmlAttribute(name = "Version", required=false)
    private Integer version;

    public Integer getVersion() { return version;  }
    public TradeRef setVersion(Integer version) 
        { this.version = version;  return this; }
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "References", propOrder = {  })
public class References  {

    private ArrayList<BusinessEntityRef> elements = new ArrayList<>();

    public void add(BusinessEntityRef businessEntityRef) {
        elements.add(businessEntityRef);
    }
}

@XmlRootElement(name="BusinessEntity")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BusinessEntity", propOrder = { "references" })
public class BusinessEntity
{
    @XmlElement(name="References")
    private References references;
}

生成用于列表的XML的结果是

<References>
    <elements xsi:type="rf:TradeRef" Version="1" ID="QR21-1"></elements>
    <elements xsi:type="rf:TransactionRef" ID="QR31-1"></elements>
</References>

我将类引用更改为List的扩展。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "References", propOrder = {  })
public class References extends ArrayList<BusinessEntityRef> {
}


@XmlRootElement(name="BusinessEntity")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BusinessEntity", propOrder = { "references" })
public class BusinessEntity
{
    @XmlElementWrapper(name="References")
    @XmlElementRef
    private References references;
}

新结果是

<References>
          <rf:TradeRef Version="1" ID="QR21-1"></rf:TradeRef>
          <rf:TransactionRef ID="QR31-1"></rf:TransactionRef>
</References>

我真的想要这个

<References>
          <rf:TradeRef xsi:type="rf:TradeRef" Version="1" ID="QR21-1"></rf:TradeRef>
          <rf:TransactionRef xsi:type="rf:TransactionRef" ID="QR31-1"></rf:TransactionRef>
</References>

0 个答案:

没有答案