Example of getTagName() method in xml dom api.


 

Example of getTagName() method in xml dom api.

In this section, you will see the example of getTagName() method of DOM api.

In this section, you will see the example of getTagName() method of DOM api.

Example of getTagName() method.

In This Example, we implement the method getTagName() and getDocumentElement().

Here we see in this code given below that getTagName() method returns the name of this Element not the value of the name attribute. The getDocumentElement() gives an XmlElement class represented the element.

In this example, we create the Dom parser by create the instance of DocumentBuilder  using DocumentBuilderFactory .

After parsing the xml file we find the root node and get the tag name as output.

The code of the program is as follows.

order.xml

<?xml version="1.0" encoding="UTF-8"?>
                    
<orders>
       <item >
           <name>Premium</name>
           <price>49.00</price>
           <qty>15</qty>
       </item>
</orders>

ExamplegetTagName.java

import org.w3c.dom.*;
import java.io.IOException;
import javax.xml.parsers.*; 
import org.w3c.dom.Document;

class ExamplegetTagName 
{
  public static void main(String[] args)  throws IOException
  {
    try{   
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    Document doc = docBuilder.parse("order.xml");
    Element root=doc.getDocumentElement();
    String nl = root.getTagName();     
    System.out.println("the output of getDocumentElement="+root);
  System.out.println("the output of getTagName="+nl);
      }catch(Exception e){}
  }
}

Output.

C:\>javac ExamplegetTagName.java

C:\>java ExamplegetTagName
the output of getDocumentElement = [orders: null]
the output of getTagName = order

Download The Example

Ads