Convert XML to collections Java

Convert XML to collections Java:

There are a multiple way to get Java Collection from XML, We have just tried to explain the simplest way.


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

public class XMLToMapCollections {
public static void main(String[] args) throws Exception {
String xmplInputForTesting = "<customHeaderTag>" + "<customContactNumber>154400-0000</customContactNumber>"
+ "<customContactNumber> </customContactNumber>" + "<customContactNumber>154400-0002</customContactNumber>"
+ "<customNumber>123</customNumber><customNumber>1111</customNumber></customHeaderTag>";

System.out.println("Your XML has been parsed successfully \n"+parsedXMLToMapJavaCollection(xmplInputForTesting));

static Map<String, List<String>> parsedXMLToMapJavaCollection(String xmplInputForTesting) throws Exception {
Map<String, List<String>> map = new HashMap<String, List<String>>();
SAXReader reader = new SAXReader();
Document doc = StringReader(xmplInputForTesting));
for (@SuppressWarnings("rawtypes")
Iterator i = doc.getRootElement().elements().iterator(); i
.hasNext();) {
Element element = (Element);
List<String> list = map.get(element.getName());
if (list == null) {
list = new ArrayList<String>();
map.put(element.getName(), list);

return map;

Your XML has been parsed successfully
{customContactNumber=[154400-0000, , 154400-0002], customNumber=[123, 1111]}

You can download Jar from MVN Repository for SAXReader


%d bloggers like this: