Search code examples
javaxmlxml-parsingxstream

Can not convert XML to Map with XStream


I need to convert XML file to a Map.
Accordingly to described here I'm trying to read some repository XML file and convert it into a Map.
But this gives me

[Fatal Error] :1:1: Content is not allowed in prolog.

error.
My XML file doesn't contain ? signs on the first line, I already removed them.
My code is

static Map<String,Object> repValues;
static String mainRepositoryXML = "common.xml";

static public void setRepValues(){
    String rootPath = Paths.get(".").toAbsolutePath().normalize().toString();
    String path = rootPath + File.separator + "src"+ File.separator + "main" + File.separator + "resources" + File.separator + "repository" + File.separator + mainRepositoryXML;
    XStream xStream = new XStream(new DomDriver());
    xStream.registerConverter(new MapEntryConverter());
    xStream.alias("root", Map.class);
    repValues = (Map<String,Object>) xStream.fromXML(path);
}

public static class MapEntryConverter implements Converter {

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

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
            Map.Entry entry = (Map.Entry) obj;
            writer.startNode(entry.getKey().toString());
            Object val = entry.getValue();
            if ( null != val ) {
                writer.setValue(val.toString());
            }
            writer.endNode();
        }

    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

        Map<String, String> map = new HashMap<String, String>();

        while(reader.hasMoreChildren()) {
            reader.moveDown();

            String key = reader.getNodeName(); // nodeName aka element's name
            String value = reader.getValue();
            map.put(key, value);

            reader.moveUp();
        }

       return map;
    }

}

The code above is actually copy pasted from the mentioned above question.
The XML file seems to be quite simple:

<general>
    <downloadsPath>C:\Users\myUserDirectory\Downloads</downloadsPath>
    <downloadsPathDocker>/Downloads</downloadsPathDocker>
    <youTube>https://www.youtube.com/</youTube>
    <eBay>https://www.ebay.com/</eBay>
    <cherryPic>https://proto.gr/sites/www.proto.gr/files/styles/large_retina/public/images/fruits/cherries.jpg</cherryPic>
    <pineApplePic>https://i.pinimg.com/564x/97/86/3e/97863e0a14b69caeea2c92537a81fb1b.jpg</pineApplePic>
    <trollPic>https://mallofnorway.com/content/uploads/2020/07/008840118.jpg</trollPic>
</general>

I'm absolutely not familiar with converting XML to Map and vice versa. Not experienced dealing with XML files with Java.
I saw all these questions here (and some more) but still couldn't find working for me solution.
What am I doing wrong?
Will really appreciate any help!


Solution

  • Two fixes, fromXML as stream (not literal string) and the root is your root:

    XStream xStream = new XStream(new DomDriver());
    xStream.registerConverter(new MapEntryConverter());
    xStream.alias("general", Map.class);
    Object o = xStream.fromXML(new FileInputStream("/home/josejuan/tmp/y.xml"));
    repValues = (Map<String,Object>) o;
    

    with output

    enter image description here