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








Question

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

Answer

import java.io.FileInputStream;
//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(
          "keyname"));
      System.out.println("\tvalue: "
          + ((Node) nodeList.item(i)).getTextContent());
    }

  }
}