Example for getElementsByTagName() method in DOM Document.


 

Example for getElementsByTagName() method in DOM Document.

In this section, you will see the example of getElementsByTagName()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:

ElementbyTagName.java:

import org.w3c.dom.*;
import java.io.File;
import java.io.IOException;
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
  {
    try{   
    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)
       {
        System.out.println(title.getFirstChild().getNodeValue());  
        }
      else{
      
      System.out.println(title.getNodeValue());
      }

        }
  }catch(Exception e){}
  }
}

the input file is order.xml:

<?xml version="1.0" encoding="UTF-8"?>
                    
<orders>
   <order>     
       <item id="19">
           <name>Premium</name>
           <price>49.00</price>
           <qty>15</qty>
       </item>
       <item>
           <name>blanket</name>
           <price>20</price>
           <qty>10</qty>
       </item>
   </order>

</orders>

Output:

c:\>javac Elementby_TagName

c:\>java Elementby_TagName  order,xml

Premeium

Blanket

Download the Code.

Ads