XML Developer’s Guide

XML Applications

This chapter demonstrates some HTML applications using XML, HTTP, DOM, and JavaScript.

The XML Document Used

In this chapter we will use the XML file called «cd_catalog.xml».

Display XML Data in an HTML Table

This example loops through each element, and displays the values of the and the elements in an HTML table:

Example

For more information about using JavaScript and the XML DOM, go to DOM Intro.

Display the First CD in an HTML div Element

This example uses a function to display the first CD element in an HTML element with >

Example

function displayCD(i) var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() if (this.readyState == 4 && this.status == 200) myFunction(this, i);
>
>;
xmlhttp.open(«GET», «cd_catalog.xml», true);
xmlhttp.send();
>

function myFunction(xml, i) var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName(«CD»);
document.getElementById(«showCD»).innerHTML =
«Artist: » +
x[i].getElementsByTagName(«ARTIST»)[0].childNodes[0].nodeValue +
«
Title: » +
x[i].getElementsByTagName(«TITLE»)[0].childNodes[0].nodeValue +
«
Year: » +
x[i].getElementsByTagName(«YEAR»)[0].childNodes[0].nodeValue;
>

To navigate between the CDs, in the example above, add a next() and previous() function:

Example

function next() <
// display the next CD, unless you are on the last CD
if (i < x.length-1) <
i++;
displayCD(i);
>
>

function previous() // display the previous CD, unless you are on the first CD
if (i > 0) i—;
displayCD(i);
>
>

Show Album Information When Clicking On a CD

The last example shows how you can display album information when the user clicks on a CD:

Example

function displayCD(i) <
document.getElementById(«showCD»).innerHTML =
«Artist: » +
x[i].getElementsByTagName(«ARTIST»)[0].childNodes[0].nodeValue +
«
Title: » +
x[i].getElementsByTagName(«TITLE»)[0].childNodes[0].nodeValue +
«
Year: » +
x[i].getElementsByTagName(«YEAR»)[0].childNodes[0].nodeValue;
>

Источник

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.

Источник

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

Источник

Читайте также:  Html ссылка для звонка
Оцените статью