Share on Google+Share on Google+

Convert text file to XML file in Java

In this Java Tutorial section, you will learn how to convert the text file into xml file using Java program.

Convert text file to XML file Java

In this section, you will learn how to convert the text file into xml file in Java language. To do this, we have used StreamResult which acts as an holder for a transformation result in XML. After that Transformer class process XML from a variety of sources and write the transformation output to a variety of sinks. Then TransformerHandler listens for SAX ContentHandler, parse events and transforms them to a result. The method startElement() and endElement of TransformerHandler class have created the tags in the xml file. The Parser invoked startElement() method at the beginning of every element and endElement() at the end of every element in the XML document.

Here is the code:

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.sax.*;

public class ToXML {

	BufferedReader in;
	StreamResult out;
	TransformerHandler th;
	AttributesImpl atts;

	public static void main(String args[]) {
		new ToXML().doit();

	public void doit() {
		try {
			in = new BufferedReader(new FileReader("C:\\pdf.txt"));
			out = new StreamResult("data.xml");
			String str;
			while ((str = in.readLine()) != null) {
		} catch (Exception e) {

	public void initXML() throws ParserConfigurationException,
			TransformerConfigurationException, SAXException {
		SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory

		th = tf.newTransformerHandler();
		Transformer serializer = th.getTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
				"{}indent-amount", "4");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		atts = new AttributesImpl();
		th.startElement("", "", "Employee", atts);

	public void process(String s) throws SAXException {
		String[] elements = s.split(" ");
		th.startElement("", "", "Data", atts);
		th.startElement("", "", "Employee_Name", atts);
		th.characters(elements[0].toCharArray(), 0, elements[0].length());
		th.endElement("", "", "Employee_Name");
		th.endElement("", "", "Data");

	public void closeXML() throws SAXException {
		th.endElement("", "", "Employee");



Posted on: November 11, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.