简体   繁体   中英

Converting XML to Java Map<String, Integer> with XStream

I'm converting XML to a Java Map with XStream. Each time I solve one problem, I run into another. Incredibly frustrating. Anyways, the XML looks something like this:

<?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>

The Java in my main that I'm using to implement this looks like this:

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

The MapEntryConverter class that I've created looks like this:

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;
  }
}

At the moment I'm getting the following exception: "Exception in thread "main" com.thoughtworks.xstream.mapper.CannotResolveClassException: root".

Can anyone explain why this is and how I could fix this?

This question seemed like it might have the answer, but I think we're using different implementations: com.thoughtworks.xstream.mapper.CannotResolveClassException

Any help would be greatly appreciated. Thanks in advance!

Try this:

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM