如何将映射封送到没有标记值的xml

时间:2014-11-07 10:45:42

标签: java xml jaxb

我有一个HashMap,我想将其转换为XML:

@XmlJavaTypeAdapter(OrdersAdapter.class)
private Map<Long, Order> orders = new LinkedHashMap<Long, Order>();

默认情况下,map会转换为<entry><key></key><value></value><entry>,但我想获取XML,其中key是属性且没有值标记。像这样:

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

使用我的程序来自github:https://github.com/pfryn/simpleTestProject/tree/master/src/pl/shop,现在我可以像这样生成xml:

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

你知道如何避免“价值”标签吗?

1 个答案:

答案 0 :(得分:3)

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

}

<强>顺序

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;

}

输出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>