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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Languages
  4. Using JAXB With XSLT to Produce HTML

Using JAXB With XSLT to Produce HTML

Blaise Doughan user avatar by
Blaise Doughan
·
Nov. 21, 12 · Interview
Like (0)
Save
Tweet
Share
21.84K 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.

Popular on DZone

  • Using QuestDB to Collect Infrastructure Metrics
  • Project Hygiene
  • Last Chance To Take the DZone 2023 DevOps Survey and Win $250! [Closes on 1/25 at 8 AM]
  • The Role of Data Governance in Data Strategy: Part II

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: