如何使用xstream将哈希图映射到XML中的键值属性 [英] How to map an Hashmap to key-value-attributes in XML using xstream

查看:116
本文介绍了如何使用xstream将哈希图映射到XML中的键值属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实体:

@XStreamAlias("entity")
public class MapTestEntity {

    @XStreamAsAttribute
    public Map<String, String> myMap = new HashMap<>();

    @XStreamAsAttribute
    public String myText;
}

我使用它与xstream像:

I use it with xstream like:

MapTestEntity e = new MapTestEntity();
e.myText = "Foo";
e.myMap.put("firstname", "homer");
e.myMap.put("lastname", "simpson");

XStream xstream = new XStream(new PureJavaReflectionProvider());
xstream.processAnnotations(MapTestEntity.class);
System.out.println(xstream.toXML(e));

并获取以下xml:

<entity myText="Foo">
  <myMap>
    <entry>
      <string>lastname</string>
      <string>simpson</string>
    </entry>
    <entry>
      <string>firstname</string>
      <string>homer</string>
    </entry>
  </myMap>
</entity>

但是,我需要将 HashMap 映射到xml中的属性像:

But I need to map the HashMap to attributes in xml like:

<entity myText="Foo" lastname="simpson" firstname="homer" />

如何使用XStream?可以使用自定义转换器或映射器吗? TIA !!

How can I do that with XStream? Can I use a custom converter or mapper or something like that? TIA!!

(当然我的代码需要确保在xml属性中不重复)。

(Of course my code needs to be ensure that are no duplicates in xml attributes.)

推荐答案

我写了一个自己的转换器:

I wrote an own Converter:

public class MapToAttributesConverter implements Converter {

    public MapToAttributesConverter() {
    }

    @Override
    public boolean canConvert(Class type) {
        return Map.class.isAssignableFrom(type);
    }

    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        Map<String, String> map = (Map<String, String>) source;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            writer.addAttribute(entry.getKey(), entry.getValue().toString());
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < reader.getAttributeCount(); i++) {
            String key = reader.getAttributeName(i);
            String value = reader.getAttribute(key);
            map.put(key, value);
        }
        return map;
    }
}

这篇关于如何使用xstream将哈希图映射到XML中的键值属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆