Java HTML / XML How to - Access values using XML keyname


We would like to know how to access values using XML keyname.


//from   www .j  av a  2  s  .  c  o m
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;

public class Main {
  public static void main(String args[]) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document doc = docBuilder.parse(new FileInputStream("data.xml"));
    Element root = doc.getDocumentElement();
    org.w3c.dom.NodeList nodeList = root.getElementsByTagName("key");
    for (int i = 0; i < nodeList.getLength(); i++) {
      System.out.print(((Node) nodeList.item(i)).getAttributes().getNamedItem(
      System.out.println("\tvalue: "
          + ((Node) nodeList.item(i)).getTextContent());