Example for Finding the Root Element in the XML File


 

Example for Finding the Root Element in the XML File

Example for Finding the Root Element in the XML File

Example for Finding the Root Element in the XML File

Example for Finding the Root Element in the XML File

In this tutorial, we will discuss about how to find the Root Element in the XML file.

The XML DOM views an XML document as a tree-structure. Contents can be updated or deleted. You can also add new element in the node tree. The first node of the tree is called Root Element.

First we create an XML file order.xml. The java and xml file both are in the same directory. For parsing the xml file we created java file.

In this file, 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 element with the getDocumentElement() and get the name of the node by getName().

XML File: order.xml

<?xml version="1.0" encoding="UTF-8"?>                 
<orders>
   <order>
         <item  itemid="15">
                <name>Silver Saddle</name>
                <price>825.00</price>
                <qty>1</qty>
         </item>
         <item  itemid="49">
                <name>Premium</name>
                <price>49.00</price>
                <qty>1</qty>
         </item>
         <item  itemid="B78">
               <name>Blanket</name>
               <price>20</price>
               <qty>10</qty>
        </item>
   </order>
</orders>

Java file: rootnode.java

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

public class rootnode 
{

 public static void main(String[] args
  {
    try{
           
        DocumentBuilderFactory fact =DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fact.newDocumentBuilder();
        Document doc = builder.parse("order.xml");
        Node node = doc.getDocumentElement();
        String root = node.getNodeName();
        System.out.println("Root Node: " + root);
       }
       catch(Exception e){}
  }
}

Output of the program:

c:\>javac rootnode.java

c:\>java rootnode

root node: orders

Download this example.

Ads