反序列化为作为 XML 属性 (Java) 提供的映射键值对

Deserialising to a map key-value pairs provided as XML attributes (Java)

我想要这个XML

<root>

  <firstTag>
    <property key="foo" value="One"/>
    <property key="bar" value="Two"/>
  </firstTag>

  <secondTag>
    <property key="foo" value="1"/>
    <property key="bar" value="2"/>
  </secondTag>

</root>

被反序列化为 Map<String, String>,以便仅考虑通过 <firstTag/> 内的属性提供的键和值。 这是所需的输出映射:

{foo=One, bar=Two}

这使用 XStream、jackson-dataformat-xml 或任何流行的解组库。

我需要为此实施 Converter

public class MyConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }

    @Override
    public void marshal(Object arg0, HierarchicalStreamWriter writer, MarshallingContext context) {}

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

        Map<String, String> map = new HashMap<String, String>();
        reader.moveDown();  // Get down to the firstTag and secondTag level.

        while(reader.hasMoreChildren()) {
            if(reader.getNodeName().equals("firstTag")) {
                while(reader.hasMoreChildren()) {
                    reader.moveDown();
                    String key = reader.getAttribute("key");
                    String value = reader.getAttribute("value");
                    map.put(key, value);
                    reader.moveUp();
                }
            }
        }
        return map;
    }
}

然后使用它:

XStream xstream = new XStream();
xstream.alias("root", java.util.Map.class);
xstream.registerConverter(new MyConverter());

String xml = ...
Map<String, String> map = (Map<String, String>) xstream.fromXML(xml);