| Refresh | Home EGTry.com

xslt transformation using jdk SAXP api


XSLTransform.java

/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.xml;


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



public class XSLTransform {

  public static void main(String[] args) throws Exception {
	  //step 1. Input XML 
	  String xml="<root/>";
	  StreamSource xmlSource=new StreamSource(new StringReader(xml));

	  
	  //step 2. xslt stylesheet
	  String xslt="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
			  +"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n"
			  +"<xsl:template match=\"/\">\n"
			  +"\n<msg>Hello</msg>\n "
			  +"</xsl:template>\n"
			  +"</xsl:stylesheet>\n";
	  
	  StreamSource xsltSource=new StreamSource(new StringReader(xslt));
	  
	  //step 3. container for the resulting xml
	  StringWriter out=new StringWriter();
	  Result xmlResult=new StreamResult(out);
	  
	  //step 4. create transformer
	  TransformerFactory factory=TransformerFactory.newInstance();
	  Transformer transform=factory.newTransformer(xsltSource);
	  
	  //do the transformation
	  transform.transform(xmlSource,xmlResult);

	  System.out.println("Input:\n"+xml);
	  System.out.println("\nstylesheet:\n"+xslt);
	  System.out.println("\nResult:\n"+out.toString());

  }
  
  public static void printNode(Node node) {
	  //node and its attributes
	  String name=node.getNodeName();
	  System.out.print("<"+name);
	  if (node.hasAttributes()) {
		  NamedNodeMap attributes=node.getAttributes();
		  for(int i=0; i<attributes.getLength(); i++) {
			  Node attribute=attributes.item(i);
			  System.out.print(" "+attribute.getNodeName()+"=\""+attribute.getNodeValue()+"\"");
		  }
		  
	  }
	  System.out.println(">");
	  
	  //get child nodes
	  NodeList childList=node.getChildNodes();
	  for(int i=0; i<childList.getLength(); i++ ) {
		  Node child=childList.item(i);
		  printNode(child);
	  }
	  
	  
	  System.out.println("</"+name+">");
	  
  }
}



Output

Input:
<root/>

stylesheet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

<msg>Hello</msg>
 </xsl:template>
</xsl:stylesheet>


Result:
<?xml version="1.0" encoding="UTF-8"?><msg>Hello</msg>