DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • How to Convert HTML to DOCX in Java

Trending

  • Chaos Engineering for Microservices
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  1. DZone
  2. Coding
  3. Languages
  4. Using JAXB With XSLT to Produce HTML

Using JAXB With XSLT to Produce HTML

By 
Blaise Doughan user avatar
Blaise Doughan
·
Nov. 21, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
23.0K Views

Join the DZone community and get the full member experience.

Join For Free

JAXB (JSR-222)enables Java to treat a domain model as XML.  In this post I will demonstrate how to leverage this by applying an XSLT stylesheet to a JAXB model to produce HTML.  This approach is often leveraged when creating JAX-RS applications.

Java Model

Below is the Java model that will be used for this example.  It represents information about a collection of books.

Library

package blog.jaxbsource.xslt;
 
import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
public class Library {
 
    private List<Book> books = new ArrayList<Book>();
 
    @XmlElement(name="book")
    public List<Book> getBooks() {
        return books;
    }
 
}

Book

package blog.jaxbsource.xslt;
 
public class Book {
 
    private String title;
    private String author;
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getAuthor() {
        return author;
    }
 
    public void setAuthor(String author) {
        this.author = author;
    }
 
}


XML Structure 
Our JAXB model can be used to produce XML documents that conform to the following XML schema.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
 
 <xs:element name="library" type="library" />
 
 <xs:complexType name="library">
  <xs:sequence>
   <xs:element name="book" type="book" minOccurs="0"
    maxOccurs="unbounded" />
  </xs:sequence>
 </xs:complexType>
 
 <xs:complexType name="book">
  <xs:sequence>
   <xs:element name="author" type="xs:string" minOccurs="0" />
   <xs:element name="title" type="xs:string" minOccurs="0" />
  </xs:sequence>
 </xs:complexType>
 
</xs:schema>

The above XML schema was produced using the following code.

package blog.jaxbsource.xslt;
 
import java.io.IOException;
import javax.xml.bind.*;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
 
public class GenSchema {
 
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Library.class);
         
        jc.generateSchema(new SchemaOutputResolver() {
 
            @Override
            public Result createOutput(String namespaceURI, String suggestedFileName)
                    throws IOException {
                StreamResult result = new StreamResult(System.out);
                result.setSystemId(suggestedFileName);
                return result;
            }
             
        });
    }
 
}


Stylesheet
Below is the XSLT stylesheet that we will use to convert the XML (JAXB model) to HTML.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/">
  <html>
   <body>
    <h2>My Library</h2>
    <table>
     <tr>
      <th>Title</th>
      <th>Author</th>
     </tr>
     <xsl:for-each select="library/book">
      <tr>
       <td>
        <xsl:value-of select="title" />
       </td>
       <td>
        <xsl:value-of select="author" />
       </td>
      </tr>
     </xsl:for-each>
    </table>
   </body>
  </html>
 </xsl:template>
</xsl:stylesheet>
Demo Code

In our demo code we will use the standard javax.xml.transform APIs to do the conversion. Our JAXB input is wrapped in an instance of JAXBSource, and the output is wrapped in an instance of StreamResult.
package blog.jaxbsource.xslt;
 
import javax.xml.bind.*;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        // XML Data
        Book book1 = new Book();
        book1.setAuthor("Jane Doe");
        book1.setTitle("Some Book");
 
        Book book2 = new Book();
        book2.setAuthor("John Smith");
        book2.setTitle("Another Novel");
         
        Library catalog = new Library();
        catalog.getBooks().add(book1);
        catalog.getBooks().add(book2);
 
        // Create Transformer
        TransformerFactory tf = TransformerFactory.newInstance();
        StreamSource xslt = new StreamSource(
                "src/blog/jaxbsource/xslt/stylesheet.xsl");
        Transformer transformer = tf.newTransformer(xslt);
 
        // Source
        JAXBContext jc = JAXBContext.newInstance(Library.class);
        JAXBSource source = new JAXBSource(jc, catalog);
 
        // Result
        StreamResult result = new StreamResult(System.out);
         
        // Transform
        transformer.transform(source, result);
    }
 
}

Output 

The following HTML output was produced as a result of running the demo code.
<?xml version="1.0" encoding="UTF-8"?>
<html>
 <body>
  <h2>My Library</h2>
  <table>
   <tr>
    <th>Title</th>
    <th>Author</th>
   </tr>
   <tr>
    <td>Some Book</td>
    <td>Jane Doe</td>
   </tr>
   <tr>
    <td>Another Novel</td>
    <td>John Smith</td>
   </tr>
  </table>
 </body>
</html>




HTML XSLT

Published at DZone with permission of Blaise Doughan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • How to Convert HTML to DOCX in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!