0

我有一个带有序列的 xml 模式。

<xs:sequence>
    <xs:element maxOccurs="unbounded" ref="x"/>
    <xs:element maxOccurs="unbounded" ref="y"/>
</xs:sequence>

在这种情况下 allx必须出现在 all 之前y。那不是我想要的。所以我尝试了选择,但是当使用它时,当我生成相应的类时,所有 x 和 y 都映射到列表中。

有没有办法在xml中没有特殊顺序的x和y单独列表?

4

1 回答 1

0

JAXB (JSR-222)实现在解组时对 XML 元素的顺序非常宽容。我将在下面用一个例子来演示。

下面是具有单独List属性的域对象。

package forum11519412;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    List<String> x;
    List<Integer> y;

}

输入.xml

以下是List混合项目的示例 XML 文档:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <y>1</y>
    <x>A</x>
    <y>2</y>
    <x>B</x>
    <y>3</y>
    <x>C</x>
</root>

演示

演示代码将解组input.xml并将其编组。

package forum11519412;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11519412/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

输出

在生成的 XML 中,内容将按顺序排列。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <x>A</x>
    <x>B</x>
    <x>C</x>
    <y>1</y>
    <y>2</y>
    <y>3</y>
</root>
于 2012-07-17T19:35:53.537 回答