The real voyage of discovery consists not in seeking new lands but seeing with new eyes.
                                - Marcel Proust
 
Поиск
Поиск

 
 
Меню навигации
Меню навигации
 
 
Проекты
Проекты
 
 
 
 
Size_box_tl   Size_box_tr
 
Unfortunately, there is no translation for this page. We have redirected you to the english version of the site. We are sorry for any inconvenience caused...

XSL - Java working with XML overview (tutorial)

Complete Source Code for all examples below

XSL is very powerfull mechnism of templating data. It can be used in many areas, such as HTML page generation, email generation and many other where you need to put your XML data in some sort of template to make it nice.

In order to do the transformation you need two things: the XML document and the XSL template. There are lots of things to know about the XSL and I suggest you to read the w3c specifications. In this overview we will do a simple example.

 

Simple Example:

You have stock list in the form of XML and you need to generate an HTML page that looks like a table with SKU's (Stock Keeping Unit) and some of their attribution

 

The XML (source):

 



  
    PIPE
    Smoking pipe
    10.90
    10
  
  
    VIO
    Violin
    99.99
    5
  



The XSL (template):

 







  
  
   
  
  



   
       

The code to work this:

 

package dp.test.xml.xls;

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.junit.Test;


public class XSLTransformExample
{

	@Test
	public void testSimpleTransformationExample() throws TransformerException {
		
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer(
				new StreamSource(XSLTransformExample.class.getResourceAsStream("stock.xsl")));
		
		final StringWriter writer = new StringWriter();
		transformer.transform(
				new StreamSource(XSLTransformExample.class.getResourceAsStream("stock.xml")), 
				new StreamResult(writer));
		
		System.out.println(writer.toString());
		
	}
	
}

The output:

 



PIPESmoking pipe10.9010
VIOViolin99.995

Summary:

  • Transformer can be obtaine through the TransformerFactory by supplying a valis XSL
  • Invoking transform method on the XML will result in streaming the result
Эта страница была обновлена: 13/04/2012 11:10


© Inspire Software, Denys Pavlov, 2005-2012
© Inspire Software, Denys Pavlov, 2005-2012
 
Size_box_bl   Size_box_br