JAXB:特定顺序的多个同类标签

时间:2016-04-06 14:09:54

标签: java xml jaxb

我有一个非常不寻常的XML格式,我需要编组和取消编组:

<a>
  <b></b>
  <c></c>
  <d></d>
  <c></c>
  <d></d>
</a>

我期望工作的代码但不是:

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(propOrder={"b", "eList"})
@XmlRootElement(name="a")
public class A {

    @XmlElement(name="b")
    private String b;

    @XmlElementRefs({
        @XmlElementRef(name="c", type=String.class),
        @XmlElementRef(name="d", type=String.class)
    })
    @XmlMixed
    private List<String> eList;
}

结果遗憾地错过了正确的顺序(我需要b,c,d,c,d顺序):

<a>
  <b></b>
  <c></c>
  <c></c>
  <d></d>
  <d></d>
</a>

我尝试了不同的东西,比如@XmlMixed,带有@XmlPath的子对象,但对我没用。任何提示或链接?提前谢谢!

1 个答案:

答案 0 :(得分:0)

I suggest you below solution

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "a", propOrder = {
    "bs",
    "cs",
    "ds"
})
@XmlRootElement(name = "a")
public class A
    implements Serializable
{

    private final static long serialVersionUID = 1234567890L;
    @XmlElement(name = "b")
    protected List<String> bs;
    @XmlElement(name = "c")
    protected List<String> cs;
    @XmlElement(name = "d")
    protected List<String> ds;

    public List<String> getBS() {
        if (bs == null) {
            bs = new ArrayList<String>();
        }
        return this.bs;
    }

    public List<String> getCS() {
        if (cs == null) {
            cs = new ArrayList<String>();
        }
        return this.cs;
    }


    public List<String> getDS() {
        if (ds == null) {
            ds = new ArrayList<String>();
        }
        return this.ds;
    }

}

and you might apply also an xsd validation.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified"
    targetNamespace="http://yourNamespace" xmlns="http://yourNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name="a" type="a" />
    <xs:complexType name="a">
        <xs:sequence>
            <xs:element name="b" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
            <xs:element name="c" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
            <xs:element name="d" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
    </xs:complexType>

</xs:schema>