Java HTML / XML How to - Parse Xml and assign attribute value to a separate variable








Question

We would like to know how to parse Xml and assign attribute value to a separate variable.

Answer

import java.io.File;
/*from   w w  w  .j  av  a 2s .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.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(new File("D:/test.xml"));

    NodeList elt = doc.getElementsByTagName("EMPLOYEE");
    for (int k = 0; k < elt.getLength(); k++) {
      Node firstNode3 = elt.item(k);
      Element elt1 = (Element) firstNode3;
      String att = elt1.getAttribute("PERMANENT");
      System.out.println("\n\nPERMANENT: " + att);

      NodeList nodes = elt1.getElementsByTagName("DETAILS");
      for (int i = 0; i < nodes.getLength(); i++) {
        Node childNode = nodes.item(i);
        Element elt2 = (Element) childNode;
        System.out.println("---" + elt2.getNodeName());
        System.out.println("NAME:" + elt2.getAttribute("NAME"));
        System.out.println("ID:" + elt2.getAttribute("ID"));
        System.out.println("AGE:" + elt2.getAttribute("AGE"));
      }
    }
  }
}