Narendra Pathai
Narendra Pathai

Reputation: 41975

Sorted Unmarshalling using JAXB

Suppose I have a XML:

<root>
   <node>
      <order-id>4</order-id>
      .....
   </node>

   <node>
      <order-id>1</order-id>
      ....
   </node>
</root>

When I unmarshal this xml I want that the List<Node> I get is be sorted with order-id value.

Is there a way using JAXB that I directly get the sorted List?

Upvotes: 3

Views: 1608

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136082

If you don't mind Set instead of List, try

@XmlRootElement(name="node")
    class Node implements Comparable<Node> {
        @XmlElement(name="order-id")
        int orderId;

        @Override
        public int compareTo(Node n) {
            return orderId - n.orderId;
        }
    }

    @XmlRootElement(name="root")
    class Root {
        @XmlElement(name="node")
        Set<Node> nodes = new TreeSet<>(); 
    }

works fine. And if Set is not an option, then change Root as

@XmlRootElement(name="root")
class Root {
    List<Node> nodes;

    @XmlElement(name="node")
    public void setNodes(Node[] nodes) {
        Arrays.sort(nodes);
        this.nodes = Arrays.asList(nodes);
    }
}

Upvotes: 6

Related Questions