How to remove the tag in XML using JAXB

2019-05-26 15:58发布

I'm using JAXB to convert java object into xml file.

In my XML file, I need to remove the tag without using XSLT .

For example :remove the tag orders

<order_List>
  <orders>
    <orderid>12324<orderid>
  </orders>
</order_List>

Excepted result :

<order_List>
   <orderid>12324<orderid>
</order_List>

1条回答
时光不老,我们不散
2楼-- · 2019-05-26 15:59

I can suggest you "naive" approach.

The wrapper tag orders can be configured using JAXB annotation @XmlElementWrapper. So, you can create 2 models: one that contain this tag, another that does not. You can use the model that contains this tag to parse you data, then copy data to model that does not contain this tag and then use it to serialize.

@XmlRootElement(name = "index-annotations")
public class OrderList {
   private Collection<Integer> orderIds;

   @XmlElement(name = "orderid", type = Integer.class)
   public Collection<Integer> getOrderId() {
       return orderIds;
   }
}


@XmlRootElement(name = "index-annotations")
public class OutputOrderList extends OrderList {
   @Override
   @XmlElement(name = "orderid", type = Integer.class)
   @XmlElementWrapper(name="orders")
   public Collection<Integer> getOrderId() {
       return orderIds;
   }
}

Obviously this solution contains a kind of duplicate code, however it is probably better then configuring 2 schemas using XML because of compile time validation of annotations validity.

查看更多
登录 后发表回答