Java HTML / XML How to - Get element text content from xml using DOM








Question

We would like to know how to get element text content from xml using DOM.

Answer

import java.io.File;
import java.io.FileInputStream;
/*from  www  . jav a2  s.co 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;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String args[]) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(new File(
        "src/file.xml"));
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc1 = builder.parse(fileInputStream);
    doc1.getDocumentElement().normalize();
    NodeList kList1 = doc1.getElementsByTagName("item");

    StringBuilder stringBuilder = new StringBuilder();

    for (int temp = 0; temp < kList1.getLength(); temp++) {
      Node kNode1 = kList1.item(temp);
      System.out.println("\nCurrent Element :" + kNode1.getNodeName());
      if (kNode1.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) kNode1;
        System.out.println("node name" + eElement.getNodeName());
        Node in = eElement.getFirstChild();
        if ((in.getTextContent() != null) && !(in.getTextContent()).isEmpty()
            && !(in.getTextContent().length() == 0))
          stringBuilder.append(in.getTextContent());
      }
    }
    System.out.println(stringBuilder);
  }
}