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:

|
Recommend the tutorial |
Ask Questions? Discuss: Java get Node Value
Post your Comment