Share on Google+Share on Google+

Example for getElementsByTagName() method in DOM Document.

In this section, you will see the example of getElementsByTagName()in DOM Document.

Example for getElementsByTagName() in DOM Document

In this section ,we will discuss the implementation of the getElementsByTagName(), getLength(), getFirstChild() methods as follows.

In this Example, we find the value of first siblings of the child in the xml document. The method getElementsByTagName() is in the interface Element which is in the package org.w3c.dom.Element.

This method retrieves any descendent elements which have a tag name of tagname. This method returns the elements with the given tag name under the present node at any sub level.

We use DocumentBuilderFactory to create the DocumentBuilder ,then we parse the XML file using the parse() method.

After parsing the document, we get the node list by getElementsByTagName("tag name") method. In this a tag name is passed as a string which is to be searched. The file name is given at run time on console by programmer.

The code of the example is as follows:

import org.w3c.dom.*;
import javax.xml.parsers.*; 
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Document;

class Elementby_TagName 
  public static void main(String[] args)  throws IOException
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File(args[0])); //input xml file on console
       NodeList nl = doc.getElementsByTagName("item");    //the tag name
        int num = nl.getLength();                                           //length of list
  for (int i = 0; i < num; i++
    Element section = (Elementnl.item(i)

       Node title = section.getFirstChild();                  //get the first child of the document
               title = title.getNextSibling();                     //get the sibling of child
       if (title != null)

  }catch(Exception e){}

the input file is order.xml:

<?xml version="1.0" encoding="UTF-8"?>
       <item id="19">



c:\>javac Elementby_TagName

c:\>java Elementby_TagName  order,xml



Download the Code.



Posted on: September 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null