How to Convert Xml to Java.Util.Map and Vice Versa

How to convert XML to java.util.Map and vice versa?

XStream!

Updated: I added unmarshal part as requested in comments..

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class Test {

public static void main(String[] args) {

Map<String,String> map = new HashMap<String,String>();
map.put("name","chris");
map.put("island","faranga");

XStream magicApi = new XStream();
magicApi.registerConverter(new MapEntryConverter());
magicApi.alias("root", Map.class);

String xml = magicApi.toXML(map);
System.out.println("Result of tweaked XStream toXml()");
System.out.println(xml);

Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);
assert extractedMap.get("name").equals("chris");
assert extractedMap.get("island").equals("faranga");

}

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

}

}

Can not convert XML to Map with XStream

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

Sample Image

Convert XML String to Map and get the key & value pairs using Java

package com.test;

import java.io.StringReader;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Random {

/**
* @param args
*/
public static void main(String[] args) {
HashMap<String, String> values = new HashMap<String, String>();
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user><kyc>123</kyc><address>test</address><resiFI>asds</resiFI></user>";
Document xml = convertStringToDocument(xmlString);
Node user = xml.getFirstChild();
NodeList childs = user.getChildNodes();
Node child;
for (int i = 0; i < childs.getLength(); i++) {
child = childs.item(i);
System.out.println(child.getNodeName());
System.out.println(child.getTextContent());
values.put(child.getNodeName(), child.getTextContent());
}

}

private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(
xmlStr)));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

This will work. Please check :)
You can play with DOM.

Java - XML to HashMap using XStream - CannotResolveClassException: Response

I'm not sure this is the exact answer, but let's try.

IMO the error is trying to map an XML directly into an HashMap, without telling XStream how to do it.

For this reason I suggest to generate a Class which reflects xml schema and a second Class which maps the first one into a Map.

For example, I put your code in this simple class:

enter code herepackage com.stackoverflow.test.xstream_xml_to_map;

import java.io.File;

import com.thoughtworks.xstream.XStream;

public class App {

public static void main(String[] args) {
XStream xStream = new XStream();
File f = new File(App.class.getClassLoader().getResource("provided.xml").getFile());
xStream.alias("Response", Response.class);
Response res = (Response) xStream.fromXML(f);
System.out.println("Credit: "+res.getCredit());
System.out.println("Status: "+res.getStatus());
}
}

using this Response class:

package com.stackoverflow.test.xstream_xml_to_map;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("Response")
public class Response {

private String Status = new String();

private String Credit = new String();

public String getStatus() {
return Status;
}

public String getCredit() {
return Credit;
}
}

with this output

Now you can use res object to generate the HashMap you prefer

Converting XML into Java Map<String, Integer>

You need to register your MapConverter, the class which implements Converter

xstream.registerConverter(new MapEntryConverter());

Hope that helps



Related Topics



Leave a reply



Submit