I have a HashMap which I want to convert to XML:
@XmlJavaTypeAdapter(OrdersAdapter.class)
private Map<Long, Order> orders = new LinkedHashMap<Long, Order>();
By default map is converted to <entry><key></key><value></value><entry>
, but I wanted to get XML, where key is attribute and there is no value tag. Something like this:
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<productsMap>
<orders>
<order orderId="1">
<prodId>123</prodId>
<price>1</price>
</order>
<order orderId="2">
<prodId>15</prodId>
<price>10</price>
</order>
</orders>
</productsMap>
Using my program from github: https://github.com/pfryn/simpleTestProject/tree/master/src/pl/shop , now I am able to generate xml like this:
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<productsMap>
<orders>
<order orderId="1">
<value>
<prodId>123</prodId>
<price>1</price>
</value>
</order>
<order orderId="2">
<value>
<prodId>15</prodId>
<price>10</price>
</value>
</order>
</orders>
</productsMap>
Do you know how to avoid "value" tag?
OrderType
public class OrderType {
public List<Order> order =
new ArrayList<Order>();
}
OrdersAdapter
public class OrdersAdapter extends XmlAdapter<OrderType, Map<Long, Order>> {
@Override
public Map<Long, Order> unmarshal(OrderType v) throws Exception {
Map<Long, Order> hashMap = new HashMap<Long, Order>();
for (Order myEntryType : v.order) {
hashMap.put(myEntryType.orderId, myEntryType);
}
return hashMap;
}
@Override
public OrderType marshal(Map<Long, Order> map) throws Exception {
OrderType ordType = new OrderType();
for (Entry<Long, Order> entry : map.entrySet()) {
Order ordEntryType =
new Order();
ordEntryType.orderId = entry.getKey();
ordEntryType.price = entry.getValue().price;
ordEntryType.prodId = entry.getValue().prodId;
ordType.order.add(ordEntryType);
}
return ordType;
}
}
Order
public class Order {
public Order(){
super();
}
public Order(Long prodId, BigDecimal price) {
this();
this.prodId = prodId;
this.price = price;
}
@XmlAttribute
public Long orderId;
public Long prodId;
public BigDecimal price;
}
OUTPUT XML
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<productsMap>
<orders>
<order orderId="1">
<prodId>123</prodId>
<price>1</price>
</order>
<order orderId="2">
<prodId>15</prodId>
<price>10</price>
</order>
</orders>
</productsMap>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.