Java HTML / XML How to - Convert xml string to list


We would like to know how to convert xml string to list.


import java.util.ArrayList;
import java.util.List;
//from w  w w .  j a va  2 s .  c  om
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

public class Main {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "<root><x>1</x><x>2</x><x>3</x><x>4</x></root>";
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("x");
    List<String> valueList = new ArrayList<String>();
    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);
      String name = element.getTextContent();
     // Element line = (Element) name.item(0);
      System.out.println("Name: " + name);