Xstream XML -> (Map) XML

황제낙엽 2011.04.29 11:32 조회 수 : 61

site_link1  
site_link2  
site_link3  
이글은 키값과 밸류값을 한 라인을 통합해서 <key>value</key>방식으로 Map을 XML로 변환할 때 적용하는 방법에 대해서 기술합니다.
XML 의 모양을 변환하여 다시 저장합니다

1. MapConverter 재정의
public class CustomMapConverter implements Converter {

private static final Logger LOG = Logger.getLogger(CustomMapConverter.class);

@Override
public boolean canConvert(Class type) {

return type.equals(HashMap.class) || type.equals(Hashtable.class)
|| type.getName().equals("java.util.LinkedHashMap")
|| type.getName().equals("sun.font.AttributeMap");
}

@Override
@SuppressWarnings("unchecked")
public void marshal(Object src, HierarchicalStreamWriter writer, MarshallingContext context) {

Map<String, Object> map = null;

try {
map = (Map<String, Object>) src;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next();
writer.startNode(entry.getKey().toString());
writer.setValue(entry.getValue().toString());
writer.endNode();
}
} catch (Exception e) {
e.printStackTrace();
LOG.error(e);
}
}

@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

// Map map = (Map) createCollection(context.getRequiredType());
// populateMap(reader, context, map);
Map<String, Object> map = new HashMap<String, Object>();
return map;
}
}

2. 사용 샘플
 - xstream.registerConverter(new CustomMapConverter());

3. 실행 결과
원본 XML
<map>
<entry>
<string>result</string>
<string>0</string>
<string>username</string>
<string>pepsi@paran.com</string>
<string>icon</string>
<string>position=30,30&;name=워드 뷰</string>
</entry>
</map>

변환 결과 XML
<node>
<result>0</result>
<username>pepsi@paran.com</username>
<icon>position=30,30&;name=워드 뷰</icon>
</node>