Visit all elements

In this chapter you will learn:

  1. Visiting All the Elements in a DOM Document

Visiting All the Elements in a DOM Document

We can call getElementsByTagName() from Document and pass in * to get all elements.

NodeList list = doc.getElementsByTagName("*");

The following code is a full runnable example to show how to get all elements from a Document.

import java.io.StringReader;
// j a  v a2 s.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.NodeList;
import org.xml.sax.InputSource;

public class Main {
  public static void main(String[] argv) throws Exception {
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));
    
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    
    Document doc = db.parse(is);
    NodeList list = doc.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
      Element element = (Element) list.item(i);
      System.out.println(element.getNodeName());
    }
  }
  static String xmlRecords = 
      "<data>" +
      "  <employee>" +
      "    <name>Tom</name>"+ 
      "    <title>Manager</title>" +
      "  </employee>" +
      "  <employee>" +
      "    <name id='web'>java2s.com</name>"+ 
      "    <title>Programmer</title>" +
      "  </employee>" +
      "</data>";
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to get element from an XML document by tag name
Home » Java Tutorial » XML

DOM Parser

    DOM
    Parse XML string
    Parse XML file with DOM Parser
    DOM Parser Error
    Output DOM Document to console
    Save DOM Document to a file
    Format a DOM Document
    Output Document to String
    Visit all elements
    Element retrieve by tag name
    Element character data retrieve
    DOM node visiting
    Node type
    DOM node dump
    Children nodes
    Root Element
    Doc Type
    Declared Entities
    External Entities resolve
    DOMImplementation

DOM Edit

    Element text child data
    Element remove
    Add text node to element
    Element text data update
    Add attribute to element
    Attribute remove
    Create new empty element
    Element clone
    CDATASection
    Comments element
    Processing Instruction
    New XML Document

SAX Parser

    SAX Parser action
    Parse an XML file with SAX parser
    SAX Parser based XML Document dump
    SAX Parser Error Handler
    SAX Parser content handler
    SAX Locator

Utility

    Encode String for XML attribute
    Convert Source to InputSource