XSD映射到Java POJO

时间:2015-05-10 10:35:31

标签: java xml xsd jaxb

假设我有来自Web服务的XML源,我无法控制,具有以下结构:

<wrapper>
    <baz>content</baz>
    <foo>
        <bar>content</bar>
        <bar>content</bar>
    </foo>
</wrapper>

相应的XSD如下:

<xsd:complexType name="wrapper">
    <xsd:element name="baz" type="xsd:string"/>
    <xsd:element name="foo" minOccurs="0" maxOccurs="1">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="bar" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:complexType>

从那个XSD开始,JAXB生成以下Java类:

@XmlType(name = "wrapper")
public class Wrapper {

    @XmlElement
    protected String baz;

    @XmlElement
    protected Foo foo;

    @XmlType(name = "foo")
    public static class Foo {

        @XmlElement
        protected List<String> bar;
    }
}

是否可以重构/注释POJO,而不是 Wrapper 具有 Foo 对象,它包含 Bar 对象列表?

如果它有助于我使用Spring-WS和使用默认的Jaxb2Marshaller来使用Web服务。

1 个答案:

答案 0 :(得分:1)

尝试添加 @XmlElementWrapper 注释。有关详细信息,请查看此answer

@XmlRootElement    
@XmlAccessorType(XmlAccessType.FIELD)
public class Wrapper {
    @XmlElement
    protected String baz;

    @XmlElement(name = "bar")
    @XmlElementWrapper(name = "foo")
    protected List<String> bars;

    public String getBaz() {
        return baz;
    }

    public void setBaz(String baz) {
        this.baz = baz;
    }

    public List<String> getBars() {
        return bars;
    }

    public void setBars(List<String> bars) {
        this.bars = bars;
    }
}