使用XStream </string,>将XML转换为Java Map <string,integer =“”>

时间:2014-08-02 18:41:11

标签: java xml map xstream

我正在使用XStream将XML转换为Java Map。每次我解决一个问题,我都遇到另一个问题。令人难以置信的沮丧。无论如何,XML看起来像这样:

<?xml version="1.0" encoding="UTF-8" ?>
    <root>
        <Durapipe type="int">1</Durapipe>
        <EXPLAIN type="int">2</EXPLAIN>
        <woods type="int">2</woods>
        <hanging type="int">3</hanging>
        <hastily type="int">2</hastily>
        <localized type="int">1</localized>
        <Schuster type="int">5</Schuster>
        ....
    </root>

我用来实现它的Java主要是这样的:

XStream xstream = new XStream();
    Map<String, Integer> englishCorpusProbDist; 
    xstream.registerConverter(new MapEntryConverter());
    englishCorpusProbDist = (Map<String, Integer>)xstream.fromXML(new File("locationOnMyComputer/frequencies.xml"));

我创建的MapEntryConverter类如下所示:

public class MapEntryConverter implements Converter {
  public class java {

    }

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

  public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
    Map<String, Integer> map = (Map<String, Integer>) value;
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      writer.startNode(entry.getKey().toString());
      writer.setValue(entry.getValue().toString());
      writer.endNode();
    }
  }

  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    Map<String, Integer> map = new HashMap<String, Integer>();

    while (reader.hasMoreChildren()) {
      reader.moveDown();
      map.put(reader.getNodeName(), new Integer(reader.getValue()));
      reader.moveUp();
    }
    return map;
  }
}

目前我收到以下异常:“线程中的异常”main“com.thoughtworks.xstream.mapper.CannotResolveClassException:root”。

任何人都可以解释为什么会这样,以及我如何解决这个问题?

这个问题似乎可能有答案,但我认为我们正在使用不同的实现:com.thoughtworks.xstream.mapper.CannotResolveClassException

非常感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个:

XStream xstream = new XStream(new DomDriver());
        xstream.alias("root", Map.class);
        Map<String, Integer> englishCorpusProbDist; 
        xstream.registerConverter(new MapEntryConverter());
        englishCorpusProbDist = (Map<String, Integer>)xstream.fromXML(new FileInputStream(new File("locationOnMyComputer/frequencies.xml")));