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.
package com.onlinetutorials.tech; import java.io.StringReader; 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; import org.dom4j.io.SAXReader; 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 = reader.read(new StringReader(xmplInputForTesting)); for (@SuppressWarnings("rawtypes") Iterator i = doc.getRootElement().elements().iterator(); i .hasNext();) { Element element = (Element) i.next(); List<String> list = map.get(element.getName()); if (list == null) { list = new ArrayList<String>(); map.put(element.getName(), list); } list.add(element.getText()); } return map; } }
Output:
Your XML has been parsed successfully
{customContactNumber=[154400-0000, , 154400-0002], customNumber=[123, 1111]}
You can download Jar from MVN Repository for SAXReader
You must log in to post a comment.