XML Developer’s Guide

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.

Читайте также:  Типы данных языка java переменные

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.

Читайте также:  Как выровнять body по центру css

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.

Источник

Конвертировать XML в HTML

Вы можете перевести xml документ в html и во множество других форматов с помощью бесплатного онлайн конвертера.

Как сконвертировать xml в html?

Загрузите xml-файл

Выберите файл, который вы хотите конвертировать с компьютера, Google Диска, Dropbox или перетащите его на страницу.

Выберите «в html»

Выберите html или любой другой формат, в который вы хотите конвертировать файл (более 200 поддерживаемых форматов)

Скачайте ваш html файл

Бесплатное онлайн преобразование xml в html

Просто перетащите ваши файлы в формате xml на страницу, чтобы конвертировать в html или вы можете преобразовать его в более чем 250 различных форматов файлов без регистрации, указывая электронную почту или водяной знак.

Мы удаляем загруженные файлы xml мгновенно и преобразованные html файлы через 24 часа. Все файлы передаются с использованием продвинутого шифрования SSL.

Вам не нужно устанавливать какое-либо программное обеспечение. Все преобразования xml в html происходят в облаке и не используют какие-либо ресурсы вашего компьютера.

Extensible Markup Language

Hypertext Markup Language with a client-side image map

FAQ

Во-первых, выберите xml файл, который вы хотите конвертировать или перетащить его. Во-вторых, выберите html или любой другой формат, в который вы хотите преобразовать файл. Затем нажмите кнопку конвертировать и подождите, пока файл не преобразуется

Преобразование Изображение обычно занимает несколько секунд. Вы преобразовать xml в html очень быстро.

Конечно! Мы удалить загруженные и преобразованные файлы, так что никто не имеет доступ к вашей информации. Все типы преобразования на OnlineConvertFree (в том числе xml в html) 100% безопасны.

Да! OnlineConvertFree не требует установки. Вы можете конвертировать любые файлы (в том числе xml в html) онлайн на вашем компьютере или мобильном телефоне.

Источник

XML to HTML Converter

Convert XML to HTML online, from any device with a modern browser like Chrome and Firefox.

Convert your XML files online. You can convert your XML documents from any platform (Windows, Linux, macOS). No registration needed. Just drag and drop your XML file on upload form, choose the desired output format and click convert button. Once conversion completed you can download your HTML file.

You even can perform more advanced conversions. For example you can convert password protected documents. Just expand LoadOptions and enter the password of your file. Or you can add a watermark to the converted HTML file. Expand the ConvertOptions and fill the fields for watermarking.

Converted HTML files are stored in the cloud. Privacy is 100% guaranteed. All documents are removed from the cloud after 24 hours.

You can convert your XML documents from anywhere, from any machine or even from a mobile device. The XML converter is always available online and is completely free.

  • Convert WORD to PDF, EXCEL to PDF, PDF to WORD, POWERPOINT to IMAGE, VSDX to PDF, HTML to DOCX, EPUB to PDF, RTF to DOCX, XPS to PDF, ODT to DOCX, ODP to PPTX and many more document formats
  • Simple way to instant convert XML to HTML
  • Convert XML from anywhere — it works on all platforms including Windows, MacOS, Android and iOS
Читайте также:  Casting objects to strings java

Free Document

Free Document Conversion, Viewer, Merger app for Windows

  • Easily convert, view or merge unlimited files on your own Windows PC.
  • Process Word, Excel, PowerPoint, PDF and more than 100 file formats.
  • No limit of file size.
  • Batch conversion of multiple files.
  • One app with rich features like Conversion, Viewer, Merger, Parser, Comparison, Signature
  • Regular FREE updates with new features coming every month

XML Extended Markup Language

XML stands for Extensible Markup Language that is similar to HTML but different in using tags for defining objects. The whole idea behind creation of XML file format was to store and transport data without being dependent on software or hardware tools. Its popularity is due to it being both human as well as machine readable. This enables it to create common data protocols in the form of objects to be stored and shared over network such as World Wide Web (WWW).

HTML Hyper Text Markup Language

HTML (Hyper Text Markup Language) is the extension for web pages created for display in browsers. Known as language of the web, HTML has evolved with requirements of new information requirements to be displayed as part of web pages. The latest variant is known as HTML 5 that gives a lot of flexibility for working with the language. HTML pages are either received from server, where these are hosted, or can be loaded from local system as well.

How to convert XML to HTML

  • Open our free XML to HTML converter website.
  • Click inside the file drop area to upload XML file or drag & drop XML file.
  • Click on Convert button. Your XML files will be uploaded and converted to HTML result format.
  • Download link of result files will be available instantly after conversion.
  • You can also send a link to the HTML file to your email address.
  • Note that file will be deleted from our servers after 24 hours and download links will stop working after this time period.

FAQ

First, you need to add a file for conversion: drag & drop your XML file or click inside the white area to choose a file. Then click the "Convert" button. When XML to HTML conversion is completed, you can download your HTML file.

Of course! The download link of HTML files will be available instantly after conversion. We delete uploaded files after 24 hours and the download links will stop working after this time period. No one has access to your files. File conversion (including XML is absolutely safe.

Yes, you can use our free XML to HTML converter on any operating system that has a web browser. Our XML to HTML converter works online and does not require any software installation.

Detailed examples are available at GitHub in the form of executable projects. If you are only interested in XML to HTML conversion then check .NET & Java examples.

Other Supported Conversions

You can also convert XML into many other file formats. Please see the complete list below.

Источник

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