Storing Data (Retrieved from a XML Document) to a File
In this section, you will learn to store data (retrieved from the XML document) to a specified file (with extension '.txt', '.doc', '.xls', '.shtml' etc.) in different formats (text, xml, html etc.).
Description of program:
This is a very simple program that helps you in storing the data to a specified file in different format. After running this program asks you a xml file name at the console. If the given file exists it parses and creates a Document object . To parse it you need the DocumentBuilderFactory and DocumentBuilder object. We create a Transformer and use the setOutputProperty() method that is an abstract method to invoke the Transformer object and sets an output property that will generate a output in desired format. In this method you set the "text" value for generating the text retrieved from the xml document.
An object of Document is passed in the DOMSource() constructor . Result object is created to show the generated file as output. Here we give a file name with extension, it creates a new file according to given file name and extension. The transform() method takes the Source and Result objects and it processes the source object to the output result. When the file is created it displays a message "File creation successfully!" Here the results are displayed in different files like: vk.txt, vk.doc, vk.xls, vk.shtml etc. from the XML document.
Here is the XML File: Employee-Detail.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_E-mail>[email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> |
Here is the Java File: StoreData.java
import java.io.*;
|
Output of program:
C:\vinod\xml>javac StoreData.java C:\vinod\xml>java StoreData Enter XML file name: Employee-Detail.xml File creation successfully! C:\vinod\xml> |