JAXB解组要映射的未定义元素?

问题描述 投票:2回答:1

我有要[[unmarshall的XML:]]<?xml version="1.0" encoding="UTF-8"?> <ROW id='1'> <MOBILE>9831138683</MOBILE> <A>1</A> <B>2</B> </ROW>

我想将其映射到

class

import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.eclipse.persistence.oxm.annotations.XmlPath; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class ROW { @XmlPath(".") @XmlJavaTypeAdapter(MapAdapter.class) private Map<String, Integer> map = new HashMap<String, Integer>(); @XmlAttribute private int id; @XmlElement(name = "MOBILE") private int mobileNo; }
为此,我尝试使用bdoughan@XmlVariableNode("key")博客:

MapAdapter:

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.eclipse.persistence.oxm.annotations.XmlVariableNode; 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) { map.put(adaptedEntry.key, adaptedEntry.value); } return map; } }
使用这种方法,所有键(MOBILE, id, A, B)都映射到Map内部。我想将所有已定义的属性idMOBILE映射到其在POJO中的属性,其余所有属性都映射到Map

如何实现?

我有一个要解组的XML:

9831138683

12
java xml jaxb marshalling unmarshalling
1个回答
1
投票
我为您提供了一个解决方案,但与您上面的尝试略有不同。

让我们学习根类:

© www.soinside.com 2019 - 2024. All rights reserved.