0

I have a xml schema with a sequence.

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

In this case all x's must occur before all y's. That is not what i want. So i tried choice but when using this, all x's and y's are mapped in on list when i generate the corresponding class.

Is there a way to have separate lists for x's and y's with no special order in the xml?

arserbin3
  • 6,010
  • 8
  • 36
  • 52
user558213
  • 69
  • 1
  • 5

1 Answers1

0

JAXB (JSR-222) implementations are quite forgiving on the order of XML elements when unmarshalling. I will demonstrate below with an example.

Root

Below is a domain object with separate List properties.

package forum11519412;

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

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

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

}

input.xml

Below is a sample XML document where the List items are mixed up:

<?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>

Demo

The demo code will unmarshal input.xml and marshal it back out.

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);
    }

}

Output

In the resulting XML, the contents will appear ordered.

<?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>
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • I believe you have a good final answer that models the result that was asked for, but OP is looking for for a way to generate the Root you provide from his XSD. Some kind of xjc binding magic, I believe, is what is being asked for. Authoring classes by hand, ignoring the schema, is bad news. – rektide Oct 11 '13 at 06:59
  • You are the author. Well. I for one was expecting xjc made classes. – rektide Oct 11 '13 at 07:00