XML Developer’s Guide

Convert XML to HTML using XSLT in Java

XSLT is a short form of ‘EXtensible Stylesheet Language Transformation’, powerful technology and used to transform XML into various formats such as HTML. In this post, we will see how to convert an XML file to HTML with the help of XSLT in Java.

Key points:

  • HTML stands for ‘Hypertext Markup Language’.
  • XML stands for ‘Extensible Markup Language’.
  • XSLT provides the ability to transform XML from one format to another.
  • XSL is used to filter and sorts the XML data and can format XML.
  • XSL can be used to define how an XML file should look like by transforming the XML file into a browser recognizable format.

2. XSL file (say stylesheet.xsl)

Sample XML file : report.xml

Sample XSL file : stylesheet.xsl

Test Case Results

Below is the Java code to generate an HTML file using above XML and XSL files: (say report.html)

Below is the generated HTML report (report.html):

HTML Report

Reference:

Author

Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks. View all posts

Читайте также:  Объекты javascript learn javascript

2 Comments

I need to read xml file, which structure is not fixed and show the xml data in key-value pair like Json formate but it should not have any braces like <[]>in an Html page
Not : xml have multiple child node inside the nodes Reply

Hi Radhe, First of all, sorry for late response. Well, I am not clear about the objective you are seeking through your question. Kindly share the sample of your xml file that you want to read and also share the sample html format that you would like to achieve. I’ll try my best to help you out. Thanks Reply

Submit a Comment Cancel reply

Subscribe to our Newsletter

About Techndeck

Techndeck.com is a blog revolves around software development & testing technologies. All published posts are simple to understand and provided with relevant & easy to implement examples.

Techndeck.com’s author is Deepak Verma aka DV who is an Automation Architect by profession, lives in Ontario (Canada) with his beautiful wife (Isha) and adorable dog (Fifi). He is crazy about technologies, fitness and traveling etc. He runs a Travel Youtube Channel as well. He created & maintains Techndeck.com

This website uses cookies to improve your experience. We’ll assume you’re ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

XSLT — Transformation

Converting XML to HTML using XSLT Transform. XML with XSLT you can do so many things. for example applying rich style sheet and represent XML document into alternative form.

Converting XML to HTML using XSLT Transform

XSLT stands for Extensible Style Language Transformation. XSLT is powerful API for applying style to a XML documents.

XML with XSLT you can applying formatting and transformation. Formatting is like CSS for applying styles. And transformation mean XSLT give you control to transform XML to another form.

Original XML document is not changed. But base on original document create new document.

Converting XML to HTML using XSL Transform

We define the web page structure tag that use for write XML document. Create a file called page.xml to entering following code.

  page heading 
article title article description
page footer

XSLT Transform

Lets start to write XSLT transform that will convert XML document and render to a HTML.

Define document type is XML along with document encoding:

Specifies the XSL Style Sheet and define the output method in tag. Default output method XML otherwise explicitly specify either TEXT or HTML.

Optionally you can also specifies the indent attribute to produce indented spaced XML output.

you can define number of templates contains using tag. Every tag contains match attributes.

process the children of the current node. In our case root element is current node.

Adding a root element that follow the following instruction,

HTML tag also process with tag. surrounding to a specified HTML tag. you can also assign style attributes to apply inline CSS.

Process the child element

Now adding a child tag you have to add new template. In match attribute you have to write full XPATH from the root element or simple write tag name.

But one thing clear if tag name use several time in your XML document and you want to apply style specific tag you have to write the full XPATH other wise you can use only tag name to XML find itself.

Example Code:

   page heading 
article title article description
page footer

Make C# Program for Converting XML to HTML using XSL Transform

Now create C# console application. using keyword to import the XML library

using System; using System.Xml; using System.Xml.Xsl; namespace XSLTransform < class myclass< static void Main(string[] args)< XslTransform myXslTransform; myXslTransform = new XslTransform(); myXslTransform.Load("page.xsl"); myXslTransform.Transform("page.xml"); >> >
  

page heading

article title

article description

side widget bar

sidebar item

page footer

Источник

Transforming XML to HTML using XSLT

Here we will see the example on transforming XML to HTML using XSLT. We can also use Java code to transform XML to HTML but that would require a many LoC to finish the job but using XSLT it is quite easy to transform. XSLT stands for XSL Transformations.

The Extensible Stylesheet Language (XSL) is a family of recommendations and styling language for defining XML document transformation and presentation. It consists of three parts:

  • XSL Transformations (XSLT) : a language for transforming XML;
  • The XML Path Language (XPath) : an expression language used by XSLT (and many other languages) to access or refer to parts of an XML document;
  • XSL Formatting Objects (XSL-FO) : an XML vocabulary for specifying formatting semantics.

Related Posts:

Wiki says the original document is not changed; rather, a new document is created based on the content of an existing one. Typically, input documents are XML files, but anything from which the processor can build an XQuery and XPath Data Model can be used, such as relational database tables or geographical information systems.

Although XSLT is designed as a special-purpose language for XML transformation, the language is Turing-complete, making it theoretically capable of arbitrary computations.

Let’s see how to use XSLT to transform XML documents into into HTML.

Prerequisites

Eclipse 2020-06, At least Java 1.8, Knowledge of HTML & XML

Project Setup

Create gradle or maven based project in Eclipse. The name of the project is java-xslt-xml-to-html.

If you are creating gradle based project in Eclipse then you can use the below build.gradle script:

plugins < id 'java-library' >sourceCompatibility = 12 targetCompatibility = 12 repositories < jcenter() >dependencies

If you are creating maven based project then you can use below pom.xml file:

 4.0.0 com.roytuts java-xslt-xml-to-html 0.0.1-SNAPSHOT jar UTF-8 at least 1.8    org.apache.maven.plugins maven-compiler-plugin 3.8.1 $ $    

XML File

Now put the below XML file books.xml under src/main/resources/xml directory.

In the below XML file you can see we have lots of data which can be easily displayed on HTML file in a table format.

Here we have root node catalog and under this we have several book nodes. We have the book id as an attribute on the book node. We will also see how to extract this id attribute using XSLT.

   Gambardella, Matthew  Computer 44.95 2000-10-01 An in-depth look at creating applications with XML.  Ralls, Kim  Fantasy 5.95 2000-12-16 A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.  Corets, Eva  Fantasy 5.95 2000-11-17 After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.  Corets, Eva  Fantasy 5.95 2001-03-10 In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.  Corets, Eva  Fantasy 5.95 2001-09-10 The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy.  Randall, Cynthia  Romance 4.95 2000-09-02 When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled.  Thurman, Paula  Romance 4.95 2000-11-02 A deep sea diver finds true love twenty thousand leagues beneath the sea.  Knorr, Stefan  Horror 4.95 2000-12-06 An anthology of horror stories about roaches, centipedes, scorpions and other insects.  Kress, Peter  Science Fiction 6.95 2000-11-02 After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.  O'Brien, Tim  Computer 36.95 2000-12-09 Microsoft's .NET initiative is explored in detail in this deep programmer's reference.  O'Brien, Tim  Computer 36.95 2000-12-01 The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.  Galos, Mike  Computer 49.95 2001-04-16 Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment.  

XSLT File

Next create the XSLT file called Xslt2Html.xsl and put it under src/main/resources/xslt directory.

Here the standard format of XSLT is to keep everything inside the tag . You also need to specify the namespace xmlns:xsl=»http://www.w3.org/1999/XSL/Transform» for the XSLT. Then we have tag that matches root node catalog and starts processing from this root node.

Next we want to select the XML data and display into HTML format. That’s why we have used HTML tags here. We have also used some css to style the alternate rows data. Then we are iterating each node (book) and selecting the values.

      table < font-family: arial, sans-serif; border-collapse: collapse; width: 100%; >td, th < border: 1px solid #dddddd; text-align: left; padding: 8px; >tr:nth-child(even) 

Books

Id Author Title Genre Price Publish Date Description

Transform XML to HTML

Write the Java class to transform the XML file data to HTML using XSLT file. We have put both XML and XSLT files under classpath and finaly transforms the XML data into HTML output. We write the output to the HTML file called books.html under the project’s root directory.

package com.roytuts.java.xslt.xml.to.html; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class XmlToHtmlTransformer < public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException < transform("xml/books.xml", "xslt/Xslt2Html.xsl"); >public static void transform(final String xml, final String xslt) throws SAXException, IOException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException < ClassLoader classloader = XmlToHtmlTransformer.class.getClassLoader(); InputStream xmlData = classloader.getResourceAsStream(xml); URL xsltURL = classloader.getResource(xslt); Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlData); Source stylesource = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm()); Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource); StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(xmlDocument), new StreamResult(stringWriter)); // write to file File file = new File("books.html"); if (!file.exists()) < file.createNewFile(); >FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write(stringWriter.toString()); bw.close(); > >

Testing the Application

Run the above main class, you will find books.html file under the project’s root directory.

Now open the books.html file in Web Browser in Eclipse. You will see the final XML data in tabular format on the Eclipse Web Browser. You can also open the output HTML file in browser.

Источник

Оцените статью