Home
Services
Industry Experience
Offshore Development
Technical Articles
IT Problem Discussion Forum
IT Mock Exams
Training Courses
Careers
About Us
Contact Us Contact Us
 

Transform XML into TEXT using XSLT

This tutorial is designed by keeping Java Software Programmers in mind.Tutorial demostrates how to convert XML file into TEXT file using XSLT.


Pre-Requisite: Programmers should have at least some basic understanding of XML, XSL, XSLT and XPath Scripting Languages.
  • Prepeare data.xml file as shown below:
    <?xml version="1.0" encoding="ISO-8859-1"?>
     <!-- main tag -->
      <Records>
       <!-- field 1 -->
         <Record>
    	   <marketing_info>
    	      <program_id>AAA01</program_id>
    	    </marketing_info>
    	    <customer>
    	      <name>
    		<first_name>user1</first_name>
    		<last_name></last_name>
    	      </name>
    	      <address>
    		<first_line>123 first line</first_line>
    		<second_line>second line</second_line>
    		<city>detroit</city>
    		<state>MI</state>
    		<zipcode>48181</zipcode>
    	      </address>
    	      <email>user1@hotmail.com</email>
    	    </customer>
         </Record>
        <!-- field 2 -->
         <Record>
    	   <marketing_info>
    	      <program_id>AAA02</program_id>
    	    </marketing_info>
    	    <customer>
    	      <name>
    		<first_name>user2</first_name>
    		<last_name></last_name>
    	      </name>
    	      <address>
    		<first_line>123 first line</first_line>
    		<second_line>second line</second_line>
    		<city>detroit</city>
    		<state>MI</state>
    		<zipcode>48182</zipcode>
    	      </address>
    	      <email>user1@hotmail.com</email>
    	    </customer>
    	</Record>
    	<!-- field 3 -->
         <Record>
    	   <marketing_info>
    	      <program_id>AAA03</program_id>
    	    </marketing_info>
    	    <customer>
    	      <name>
    		<first_name>user3</first_name>
    		<last_name>owen</last_name>
    	      </name>
    	      <address>
    		<first_line>345 first line</first_line>
    		<second_line>second line</second_line>
    		<city>canton</city>
    		<state>MI</state>
    		<zipcode>48183</zipcode>
    	      </address>
    	      <email>user3@hotmail.com</email>
    	    </customer>
    	</Record>
    	<!-- field 4 -->
    	     <Record>
    		   <marketing_info>
    		      <program_id>AAA02</program_id>
    		    </marketing_info>
    		    <customer>
    		      <name>
    			<first_name>user4</first_name>
    			<last_name>owen</last_name>
    		      </name>
    		      <address>
    			<first_line>456 first line</first_line>
    			<second_line>second line</second_line>
    			<city>canton</city>
    			<state>MI</state>
    			<zipcode>48184</zipcode>
    		      </address>
    		      <email>user4@hotmail.com</email>
    		    </customer>
    		</Record>
       <!-- main tag -->
       </Records>
     
  • Prepeare data.xsl file as shown below:
    <?xml version="1.0"?>
    <xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0" >
    <xsl:output method = "text" encoding="ISO-8859-1" indent="yes"/>
    <xsl:template match="Records">
    <xsl:apply-templates select="Record"/>
    </xsl:template>
    <xsl:template match="Record">
    <xsl:variable name="email" select="customer/email"/>
    <xsl:variable name="zipcode" select="customer/address/zipcode"/>
    <xsl:variable name="first_name" select="customer/name/first_name"/>
    <xsl:variable name="mktcode" select="marketing_info/program_id"/>
    <xsl:if test="$mktcode='AAA01'">
    01<xsl:text>|</xsl:text><xsl:value-of select="$first_name"/><xsl:text>|</xsl:text>
    <xsl:value-of select="$zipcode"/><xsl:text>|</xsl:text><xsl:value-of select="$email"/>
    </xsl:if>
    <xsl:if test="$mktcode='AAA02'">
    02<xsl:text>|</xsl:text><xsl:value-of select="$first_name"/><xsl:text>|</xsl:text>
    <xsl:value-of select="$zipcode"/><xsl:text>|</xsl:text><xsl:value-of select="$email"/>
    </xsl:if>
    <xsl:if test="$mktcode='AAA03'">
    03<xsl:text>|</xsl:text><xsl:value-of select="$first_name"/><xsl:text>|</xsl:text>
    <xsl:value-of select="$zipcode"/><xsl:text>|</xsl:text><xsl:value-of select="$email"/>
    </xsl:if>
    <xsl:text>
    </xsl:text>
    </xsl:template>
    </xsl:stylesheet>
    
  • Copy the above data.xml and data.xsl into "C:" drive.

  • Prepare XMLErrorChecker.java as shown below:
    package test.com;
    
    import javax.xml.transform.ErrorListener;
    import javax.xml.transform.TransformerException;
    
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.SAXParseException;
    /*
     * This class is used to catch XML errors
     * ErrorListener for the TranFormation errorHandler
     * DefaultHandler for the DocumentBuilder errorHandler
     *
     */
    public class XMLErrorChecker extends DefaultHandler implements ErrorListener {
    
    	public XMLErrorChecker() {
    
    	}
    
    	public void error(SAXParseException e) {
    	 System.out.println(
    			"SAXParseException Error-Parsing error:  " + e.getMessage());
    	}
    
    	public void warning(SAXParseException e) {
    	 System.out.println(
    			"SAXParseException Warning- Parsing problem:  " + e.getMessage());
    	}
    
    	public void fatalError(SAXParseException e) {
    	 System.out.println(
    			"SAXParseException FatalError-Parsing error:  " + e.getMessage());
    		System.out.println("Cannot continue.");
    		System.exit(1);
    	}
    
    	public void error(TransformerException te) {
    		System.out.println(
    			"TransformerException Error-Parsing error:  " + te.getMessage());
    	}
    
    	public void warning(TransformerException te) {
    		System.out.println(
    			"TransformerException Warning- Parsing problem:  "
    				+ te.getMessage());
    	}
    
    	public void fatalError(TransformerException te) {
    		System.out.println(
    			"TransformerException FatalError-Parsing error:  "
    				+ te.getMessage());
    		System.out.println("Cannot continue.");
    		System.exit(1);
    	}
    
    }
    
    
  • Prepare TranformXML.java as shown below:
    package test.com;
    import java.io.BufferedWriter;
    import java.io.ByteArrayOutputStream;
    import java.io.FileWriter;
    import java.io.OutputStreamWriter;
    import java.io.StringReader;
    import java.util.Properties;
    
    import javax.xml.transform.ErrorListener;
    import javax.xml.transform.Templates;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.Source;
    import javax.xml.transform.Result;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.OutputKeys;
    import java.io.*;
    import java.util.*;
    
    /**
     * This class is used to transform XML file to TEXT (Del) file using XSL.
     */
    public class TranformXML {
    
     public static void main(String args[]) {
    
    try {
    
       long startTime = System.currentTimeMillis();
    
       System.out.println("Transformation Process is Started :");
    
       String xmlFile = "c:\\data.xml";
       String xslFile = "c:\\data.xsl";
       String xltFile = "c:\\data.txt";
    
    	// check the file existance
    	File f = new File(xmlFile);
    
    	if (!f.exists()) {
      	   System.out.println("XML File does not exist : " + xmlFile);
    	   System.exit(0);
    	}
    
    	f = new File(xslFile);
    
    	if (!f.exists()) {
    	  System.out.println("XSL File does not exist : " + xslFile);
    	  System.exit(0);
    			}
    
    		// create a transform factory instance
    		TransformerFactory tfactory = TransformerFactory.newInstance();
    
    		// create template instance
    		Templates templates =
    			(Templates) tfactory.newTemplates(new StreamSource(xslFile));
    
    		//maintain XML identation
    		Properties oprops = templates.getOutputProperties();
    		oprops.put(OutputKeys.INDENT, "yes");
    
    		//create a tarnsformer object
    		Transformer transformer = templates.newTransformer();
    		transformer.setOutputProperties(oprops);
    
    		ByteArrayOutputStream ba = new ByteArrayOutputStream();
    		String encoding = "ISO-8859-1";
    		// set encoding
    		 OutputStreamWriter output = new OutputStreamWriter(ba, encoding);
    
    		// seting up errorlistener to transformer object
    		XMLErrorChecker errors = new XMLErrorChecker();
    		transformer.setErrorListener(errors);
    
    	//We can also use XML String or XSL String incase of file
            // : transformer.transform(new StreamSource(new StringReader(xmlFile)),new StreamResult(output));
    		transformer.transform(
    			new StreamSource(xmlFile),
    			new StreamResult(output));
    
    		System.out.println("Output Result:");
    		System.out.println(ba.toString(encoding));
    		// creating xslt File
    
    		FileWriter fw = new FileWriter(xltFile);
    		BufferedWriter bw = new BufferedWriter(fw);
    
    		bw.write(ba.toString(encoding));
    		// closing file
    		bw.close();
    		fw.close();
    		long endTime = System.currentTimeMillis();
    		System.out.println("XSLT File is created: " + xltFile);
    		System.out.println(
    		  "Total Time Taken (in Sec) to Complete the Transformation : "
    			+ (double) ((endTime - startTime) / 1000.0));
    
    		} catch (TransformerException te) {
    			System.out.println("TransformerException");
    			te.printStackTrace(System.out);
    		} catch (Exception e) {
    			e.printStackTrace(System.out);
    		}
    
    	}
    
    }
    
    
  • Set xalan.jar file in your build and runtime classpath.

  • Compile the XMLErrorChecker.java and TranformXML.java.

  • Run the test.com.TranformXML.java program.

  • You should see the following output in the console:
    Transformation Process is Started :
    Output Result:
    01|user1|48188|user1@hotmail.com
    02|user2|48188|user1@hotmail.com
    03|user3|48188|user3@hotmail.com
    02|user4|48188|user3@hotmail.com
    
    XSLT File should be created: c:\dc\data.txt
    Total Time Taken (in Sec) to Complete the Transformation: 0.485
    

  • A data.txt file should be created under "C:" drive after the successful execution of TransformXML.java.

  • data.txt file should contains the following result:
    01|user1|48181|user1@hotmail.com
    02|user2|48182|user1@hotmail.com
    03|user3|48183|user3@hotmail.com
    02|user4|48184|user4@hotmail.com
    


For additonal details, please contact Author at tpatel@itexps.com