Convert XML to HTML in Java using XSLT example

In this tutorial, let us convert XML to HTML using XSLT (Extensible Stylesheet Language Transformations) language. It is very simple to convert XML to any other formats such as HTML, plain text, etc.. using XSLT. For generating XML from table data, you can visit my earlier tutorial Java to convert table data to XML and vice versa.

Now let us convert the below XML to html using XSLT.

XML:

 

Store the XML in a file called product.xml

Now let us create XSLT for generating html for producing the below output.

html output

XSLT:

 

Store the above xslt in a file called product.xsl

Now let us write Java code for converting the above XML to HTML.

XmlToHtml.java

 

In the above java program, the method convertXMLToHTML accepts two arguments i.e xml and xslt. Create an instance of Transformer class using TransformerFactory.newTransformer method based on xslt. Use transform method of the transformer object to convert the input XML to any other format like html.

Running the above program will generate the product.html at the folder d:\template

Running the html will output the following result.

html output

Source: https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/Transformer.html

You may also like

Leave a Reply

1 Comment on "Convert XML to HTML in Java using XSLT example"


Guest
Jeevan
8 months 13 days ago

I am having only xml File . I dont know how to get xsl file from it . But my mail aim is to convert xml to html in java.Is there any way . Can u please suggest me