Get XML Elements

In this section you will learn to develop a simple java program to get the names of all elements contained in the XML document .

Get XML Elements

Get XML Elements

     

In this section you will learn to develop a simple java program to get the names of all elements contained in the XML document .

Description of the program:

The following program teaches to parse the elements and retrieve  their names, from a  XML document.    

Create a java file to retrieve the starting elements. When you run this program it asks for a XML document. This is used as a command line argument. If  you don't enter any file, the program throws an exception displaying "java.lang.ArrayIndexOutOfBoundsException: 0 at XMLElements.main( XML Elements.java:17)". 

The parse() method of SAXParser class reads the contents. The SAXParserFactory  is a factory API that enables applications to configure and obtain a SAX  parser to parse XML documents. The startElement() method retrieves all starting elements and prints them on the console. Whenever an error  occurs  it throws the SAXException.  

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>
<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak </Emp_Name>
<Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>

</Employee-Detail>

Here is the Java File: XMLElements.java

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XMLElements{
  public static void main(String[] args) {
  try{
  SAXParserFactory parserFact = SAXParserFactory.newInstance();
  SAXParser parser = parserFact.newSAXParser();
  System.out.println("XML Elements: ");
  DefaultHandler handler = new DefaultHandler(){
  public void startElement(String uri, String lName, 
  String ele, Attributes attributes
)throws SAXException{
  //print elements of xml
  System.out.println(ele);
  }
  };
  parser.parse(args[0], handler);
  }
  catch (Exception e){
  e.printStackTrace();
  }
  }
}

Download this example 

Output of program:

C:\vinod\xml\comXML>javac XMLElements.java

C:\vinod\xml\comXML>java XMLElements Employee-Detail.xml
XML Elements:
Employee-Detail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail