[英]How to add an additional XML element for polymorphic types with JAXB
我使用JAXB序列化Java對象,並且需要以下XML輸出:
<attribute>
<type>
<listType>
<itemType>
<simpleType>
<dataLength>80</dataLength>
<dataType>string</dataType>
<decimalPlaces>0</decimalPlaces>
</simpleType>
</itemType>
</listType>
</type>
</attribute>
我的Java類如下所示:
Attribute.java
@XmlRootElement
public class Attribute
{
private Type type;
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
}
Type.java
public abstract class Type
{
}
SimpleType.java
public class SimpleType extends Type
{
private int dataLength;
private int decimalPlaces;
private String dataType;
// getters and setters...
}
ListType.java
public class ListType extends Type
{
private Type itemType;
// getters and setters...
}
ComplexType.java
public class ComplexType extends Type
{
private List<Attribute> attributes = new ArrayList<>();
// getters and setters...
}
沒有任何其他注釋,JAXB會產生以下結果:
<attribute>
<type xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="listType">
<itemType xsi:type="simpleType">
<dataLength>80</dataLength>
<dataType>string</dataType>
<decimalPlaces>0</decimalPlaces>
</itemType>
</type>
</attribute>
我不希望將類型信息表示為XML屬性(xsi:type),而是希望有一個附加的XML元素,如頂部的XML代碼所示。 我認為這是一個典型的用例,但是我什么也沒找到。 我有哪些可能性?
如果類結構反映了XML結構,那么您應該不會有問題。 否則,JAXB需要使用xsi:type來區分您在屬性對象中擁有的多態類型字段-它還可以如何重構POJO?
public class Type {
private ListType listType;
}
public class ListType {
private ItemType itemType;
}
public class ItemType {
private SimpleType simpleType;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.