Home Java Java-get-example Java get Node Value
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java get Node Value

Advertisement
In this section, you will learn how to obtain the node value. Before any further processing, you need a XML file. For this we have create a employee.xml file.

Java get Node Value

     

In this section, you will learn how to obtain the node value. Before any further processing, you need a XML file. For this we have create a employee.xml file. Now to read the 'employee.xml' file, we have used DocumentBuilderFactory to enable application to obtain a parser  Then the DocumentBuilder  parse and build the XML document. The Document class access the document's data.

builder.parse(file)- This method parse the content of 'employee.xml' file as an XML document an return the DOM object.
getDocumentElement()- This method allows direct access to the child node that is the root element.
getNodeName()- This method returns the node name.
doc.getElementsByTagName("employee")-This method returns the list of nodes of all the Elements with a given tag name.
getChildNodes()-This method provides all the children of this node.
getNodeValue()- This method returns the node value.

Here is the 'employee.xml' file

<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee>
<firstname>Anusmita</firstname>
<lastname>Singh</lastname>
</employee>
</company>

Here is the code of GetNodeValue

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

public class GetNodeValue {
    public static void main(String[] args) throws Exception {
        File file = new File("employee.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        new GetNodeValue().GettingText(doc);
    }
    public void GettingText(Document doc) {
       Element e = doc.getDocumentElement();
        NodeList nodeList = doc.getElementsByTagName("employee");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                NodeList nodelist = element.getElementsByTagName("firstname");
                Element element1 = (Element) nodelist.item(0);
                NodeList fstNm = element1.getChildNodes();
                System.out.print("First Name : " + (fstNm.item(0)).getNodeValue());
               }
        }
    }
}

Output will be displayed as:

Download Source Code

Advertisement

Liked it!  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.

Posted on: November 1, 2008

Ask Questions?    Discuss: Java get Node Value  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com