1

I'm trying to convert XML Code into a Java Map. The XML (int a different file) looks something like this, and matches words with numbers (a probability distribution):

<?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>
   <regularize type="int">1</regularize>
   <LASR type="int">1</LASR>
   <LAST type="int">22</LAST>
   <Gelch type="int">2</Gelch>
   <Gelco type="int">26</Gelco>
   .......
</root>

The Java code that I'm using currently looks like this:

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

And I'm getting an exception:

Exception in thread "main" com.thoughtworks.xstream.mapper.CannotResolveClassException: root
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:79)

It was suggested that I register my Converter using the following:

xstream.registerConverter(new MapEntryConverter());

The problem with that is that MapEntryConverter doesn't seem to be a class in XStream, and I'm confused with this person's suggestion.

Here's the previous question I asked about this with the person's response: Converting XML into Java Map<String, Integer>

Any help would be much appreciated. Thank you in advance!

Community
  • 1
  • 1
user3246779
  • 125
  • 3
  • 12

1 Answers1

2

You actually need to implement your own *MapConverter which extends Converter; there is no actual class called MapConverter which is something I was confused with for a while as well.

Have a look at one that I've implemented and have on Github. I hope this would make things more understandable. You basically have to tell XStream what to do when marshalling and unmarshalling the data related to the respective tag.

carlspring
  • 31,231
  • 29
  • 115
  • 197
  • 1
    Don't forget to register the converter (`xstream.registerConverter(...);`). – carlspring Aug 02 '14 at 16:06
  • 1
    Looks like your GitHub link has gone stale because you changed the code so much. Here is a permanent link to the file you mentioned https://github.com/strongbox/strongbox/blob/d7d3471a1164af651bc35ec66797ada21f375856/strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/configuration/StorageMapEntryConverter.java – Vlad Mar 17 '16 at 23:39
  • 1
    @Vlad, thanks for pointing that out! You know how it goes with active projects -- things change. At one point I got really fed up with XStream and replaced all my code with JAXB, hence this code "disappeared". I've updated the link to the permanent revision. Thanks! (And, honestly, if you can use JAXB, just do it. It'll make your life easier). – carlspring Mar 18 '16 at 10:58