Java HTML / XML How to - Parse XML and populating into Map








Question

We would like to know how to parse XML and populating into Map.

Answer

import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
/*w  w  w . ja v a 2  s .c  o  m*/
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

public class Main {

  public static void main(String[] args) throws Exception {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("data.xml"));
    xsr.nextTag(); // advance to Employees tag
    xsr.nextTag(); // advance to first Employer element
    Map<String, String> map = new HashMap<String, String>();
    while (xsr.getLocalName().equals("Employee")) {
      map.put(xsr.getAttributeValue("", "id"), xsr.getElementText());
      xsr.nextTag(); // advance to next Employer element
    }
  }

}