Java HTML / XML How to - Extract attribute values








Question

We would like to know how to extract attribute values.

Answer

import java.io.File;
// w  ww.  j  av  a2  s.c  om
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File("yourFile.xml"));
    NodeList nodeList = document.getElementsByTagName("message");
    for (int x = 0, size = nodeList.getLength(); x < size; x++) {
      System.out.println(nodeList.item(x).getAttributes().getNamedItem("to")
          .getNodeValue());
    }
  }
}