处理 JAXB 集合

2022-01-19 00:00:00 java jaxb

我正在尝试使用 JAXB 解组以下 XML:

I am trying to unmarshall the following XML using JAXB:

<Works>
    <Work>
        <Composers>
            <Composer>
                <Name>A name</Name>
            </Composer>
            <Composer>
                <Name>A name 2</Name>
            </Composer>
        </Composers>
    </Work>
</Works>

我已经使用 XJC 生成了所有的类.如果我想访问 Composers 集合,我必须这样做:

I have generated all of the classes using XJC. If I want to access the Composers collection, I have to do this:

 List<Composer> composers = work.getComposers().getComposer();

有什么方法可以代替我执行以下操作吗?

Is there any way I can do the following instead?

 List<Composer> composers = work.getComposers();

我很欣赏对 Composers 对象的需求,因为它从 XML 派生,但是在处理 Java 时,拥有一个存储集合的中间 POJO 似乎有点多余.

I appreciate the need for a Composers object as it derived from the XML, but when dealing in Java, having an intermediate POJO that stores the collections seems a bit redundant.

我的 XSD 是:

<xsd:complexType name="Works">
    <xsd:sequence>
        <xsd:element name="Work" type="Work" maxOccurs="unbounded" minOccurs="0"></xsd:element>
    </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="Work">
    <xsd:sequence>
        <xsd:element name="Composers" type="Composers"></xsd:element>
    </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="Composers">
    <xsd:sequence>
        <xsd:element name="Composer" type="Composer" maxOccurs="unbounded" minOccurs="0"></xsd:element>
    </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="Composer">
    <xsd:sequence>
        <xsd:element name="Name" type="xsd:string"></xsd:element>
    </xsd:sequence>
</xsd:complexType>

推荐答案

@XmlElementWrapper 插件完全符合您的要求.

The @XmlElementWrapper plugin does exactly what you want.

相关文章