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>