Java get Node Text

In this section, you will learn how to obtain the text of the node in the
specified XML file. For this we have create a 'employee.xml' file. In the given
example, we have used XMLInputFactory class in order to get the
streams. The class XMLStreamReader reads the entire XML data in
the most efficient way.
streamReader.nextTag()- This method of XMLStreamReader class skips
any white space, comment, or processing element, until a start element or end
element is reached.
streamReader.next()- This method returns the next parsing event.
streamReader.getText()- This method returns the current value of the
event.
Understand with Example
In the given below program code, we want to describe you how to obtain the
text of the node in the java application from specified XML File. For this we create a xml file name
"employee.xml".In order to get the text of the node specified in a XML
file, we have a class name GetNodeText,Inside this class we have a main method
in which we assign a memory to the object of file class that accept xml file as argument. The
XmlInputFactory call a new instance method to obtain the streams from a
xml file. The next Tag( ) method of Stream Reader class skips white space
comments or elements in processing,untill a start element is reached. The next(
) method of Stream Reader class returns you the next parsing events. The get
Text( ) returns you the current value of the event .On the Execution of
GetNodeText.java you get the text of the node specified in
"employee.xml" xml file.
Here is the 'employee.xml'
<?xml version="1.0"
encoding="UTF-8"?>
<company>
<employee>
<firstname>Anusmita</firstname>
<lastname>Singh</lastname>
</employee>
</company> |
Here is the code of GetNodeText.java
import java.io.File;
import javax.xml.stream.*;
import java.io.FileInputStream;
public class GetNodeText {
public static void main(String[] args) throws Exception {
File file = new File("employee.xml");
XMLInputFactory Factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = Factory.createXMLStreamReader
(new FileInputStream(file));
int nodeId = streamReader.nextTag();
nodeId = streamReader.nextTag();
nodeId = streamReader.next();
nodeId = streamReader.next();
nodeId = streamReader.next();
System.out.println("Text of node firstname is: " + streamReader.getText());
nodeId = streamReader.nextTag();
nodeId = streamReader.next();
nodeId = streamReader.next();
nodeId = streamReader.next();
System.out.println("Text of node lastname is: " + streamReader.getText());
}
}
|
Output will be displayed as:

Download Source Code

|