Java XML to Map Class (XML2MAP)

This post was written by Brandon on December 8, 2010
Posted Under: Java

Wow, It has been such a long time since I made a post here!
I am going to try and start posting more often instead of letting this blog die out.

I have been developing my own Twitter client, and I needed a simple way to access elements from an XML document. Unlike PHP, Java can not use strings as array indexes, so I took the route of maps. I made this class to convert an XML file to a Map, where you can access the individual elements by using the key name. This is ONLY useful if the XML document only has one set of elements, as they will be overwritten.

You need the Org.Json library from for this to work.

import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.json.*;
public class XMLToMap{
  String inXML;
  public XMLToMap(String inXML){
    this.inXML = inXML;
  public Map toMap(){
    Map<String, String> xmlmap = new HashMap<String, String>();
    ByteArrayInputStream bs = new ByteArrayInputStream(this.inXML.getBytes());
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(bs);
      NodeList mainNode = (NodeList)doc.getDocumentElement();
      Node fstNode = (Node)mainNode;
      NodeList list = ((Element)fstNode).getElementsByTagName("*");
      Element fstNmElmnt;
      String elementValue = "";
      for (int i=0; i
<list.getLength(); i++) {
        Element element = (Element)list.item(i);
          fstNmElmnt = (Element) ((NodeList)((Element)fstNode).getElementsByTagName(element.getNodeName())).item(0);
          elementValue = ((Node) fstNmElmnt.getChildNodes().item(0)).getNodeValue();
          xmlmap.put(element.getNodeName(), elementValue);
        }catch(Exception e){}
    } catch (Exception e) {
    return xmlmap;

How do you use it?
Declare a new XMLToMap object and pass the full XML document to the constructor.

XMLToMap xmlmap = new XMLToMap(fullXMLDocument);

Then call tomap and place the data back into a map object, and then you can access whatever elements you need:

Map mymap = xmlmap.toMap();

Now, I am sure this can be implemented in a much cleaner way, but it worked perfectly in this way for what I needed it for.

Add a Comment

required, use real name
required, will not be published
optional, your blog address