I'm converting XML code to a Java Map. The XML matches a large number of random words with a number (a probability distribution) and looks 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>
.......
</root>
I'm trying to implement this with XStream. Here's the Java code that my main program currently uses:
XStream xstream = new XStream();
Map<String, Integer> englishCorpusProbDist;
xstream.registerConverter(new MapEntryConverter());
englishCorpusProbDist = (Map<String, Integer>)xstream.fromXML(new File("C:/Users/David Naber/Documents/IREP Project/frequencies.xml"));
And here's my MapEntryConverterClass:
public class MapEntryConverter implements Converter {
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(), reader.getValue());
reader.moveUp();
}
return map;
}
}
I"m getting an error in the above function, on the line "map.put(reader.getNodeName(), reader.getValue());". The error says: "The method put(String, Integer) in the type Map is not applicable for the arguments (String, String)."
So I really have two questions here. First of all, why is this error happening and how can I fix it? Secondly, what more will I need to implement to finally get XStream to convert this to XML?
Any help is much appreciated. Thank you in advance!
Yes error is correct reader.getValue()
is giving String , You must have to Type Cast it in Integer
Change below code
map.put(reader.getNodeName(), reader.getValue());
to
map.put(reader.getNodeName(), new Integer(reader.getValue()));