2
我想將xml文件轉換爲java映射。 XML使用xstream映射鍵值xml對到java映射
<Person>
<ID>123</ID>
<Demographics>
<LastName>ABC</LastName>
<FirstName>XYZ</FirstName>
</Demographics>
<Married>YES</Married>
</Person>
的XStream的代碼如下:
final XStream xstream = new XStream();
xstream.alias("Person", Map.class);
xstream.alias("Demographics", Map.class);
xstream.registerConverter(new MapEntryConverter());
final Map<String, Object> map2 = (Map<String, Object>) xstream.fromXML(xml);//where xml is above defined string.
定製MapEntryConverter是:
public class MapEntryConverter implements Converter
{
public boolean canConvert(final Class clazz)
{
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(final Object value, final HierarchicalStreamWriter writer, final MarshallingContext context)
{
final AbstractMap<String, String> map = (AbstractMap<String, String>) value;
for (final Entry<String, String> entry : map.entrySet())
{
writer.startNode(entry.getKey().toString());
writer.setValue(entry.getValue().toString());
writer.endNode();
}
}
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context)
{
final Map<String, String> map = new HashMap<String, String>();
while (reader.hasMoreChildren())
{
reader.moveDown();
map.put(reader.getNodeName(), reader.getValue());
reader.moveUp();
}
return map;
}
}
所以地圖現在僅由ID和已婚的作爲鍵 - 值對。它不會將人口統計信息父級轉換爲其相應的名稱值對。
我想所有的標籤名稱作爲鍵和他們的值作爲地圖值。