使用JAXB(Moxy)解组复杂的XML

时间:2014-11-24 17:43:46

标签: java jaxb moxy

我想使用EclipseLink JAXB (MOXy)

解组以下xml
<MyObject>
    <Value1>1</Value1>
    <Value2>2</Value2>
    ...
    <ValueN>N</ValueN>
    <Items>
        <Item>
            <Value4>4</Value4>
            ...
            <ValueM>M</ValueM>
        </Item>
        ...
    </Items>
</MyObject>

节点Value1,Value2等是变量。

为此,我使用以下课程

@XmlRootElement(name="MyObject")
public class MyObject {

    public MyObject() {
        this.items = new ArrayList<Item>();
    }

    @XmlPath(".")
    @XmlJavaTypeAdapter(MyMapAdapter.class)
    private Map<String, String> map = new HashMap<String, String>();

    private List<Item> items;

    public List<Item> getItems() {
        return items;
    }

    @XmlElementWrapper(name="Items")
    @XmlElement(name="Item")
    public void setItems(List<Item> items) {
        this.items = items;
    }
}

在MyMapAdapter中,我获得了一个Value节点列表及其“值”。如果我删除“map”属性,则列表的值将正确加载。

这是MyMapAdapter:

public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, String>> {

public static class AdaptedMap {
    @XmlVariableNode("key")
    List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
}

public static class AdaptedEntry {
    @XmlTransient
    public String key;

    @XmlValue
    public String value;
}

@Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
    AdaptedMap adaptedMap = new AdaptedMap();

    for(Entry<String, String> entry : map.entrySet()) {
        AdaptedEntry adaptedEntry = new AdaptedEntry();
        adaptedEntry.key = entry.getKey();
        adaptedEntry.value = entry.getValue();
        adaptedMap.entries.add(adaptedEntry);
    }

    return adaptedMap;
}

@Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
    List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
    Map<String, String> map = new HashMap<String, String>(adaptedEntries.size());

    for(AdaptedEntry adaptedEntry : adaptedEntries) {
        if(!"Items".equals(adaptedEntry.key)){
            map.put(adaptedEntry.key, adaptedEntry.value);
        }
    }

    return map;
}

}

我做错了什么?怎么做到这一点?

任何帮助都会受到极大关注

0 个答案:

没有答案