Giới thiệu
Ở đây chúng ta sẽ thấy ví dụ về việc chuyển đổi XML thành HTML bằng XSLT. Chúng ta cũng có thể sử dụng mã Java để chuyển đổi XML thành HTML nhưng điều đó sẽ yêu cầu nhiều LỘC để hoàn thành công việc nhưng sử dụng XSLT, nó khá dễ dàng để chuyển đổi. & NBSP; XSLT là viết tắt của các biến đổi XSL.
Ngôn ngữ biểu định kiểu mở rộng (XSL) là một gia đình đề xuất và ngôn ngữ kiểu dáng để xác định chuyển đổi và trình bày tài liệu XML. Nó bao gồm ba phần:
- Các phép biến đổi XSL (XSLT): Ngôn ngữ để chuyển đổi XML; : a language for transforming XML;
- Ngôn ngữ đường dẫn XML (XPath): Ngôn ngữ biểu thức được sử dụng bởi XSLT (và nhiều ngôn ngữ khác) để truy cập hoặc tham khảo các phần của tài liệu XML; : an expression language used by XSLT (and many other languages) to access or refer to parts of an XML document;
- Các đối tượng định dạng XSL (XSL-FO): Từ vựng XML để chỉ định ngữ nghĩa định dạng. : an XML vocabulary for specifying formatting semantics.
Bài viết liên quan:
- Cách xóa không gian tên khỏi XML bằng XSLT
Wiki nói rằng tài liệu gốc không thay đổi; Thay vào đó, một tài liệu mới được tạo dựa trên nội dung của một tài liệu hiện có. Thông thường, các tài liệu đầu vào là các tệp XML, nhưng bất cứ điều gì mà bộ xử lý có thể xây dựng mô hình dữ liệu XQuery và XPath có thể được sử dụng, chẳng hạn như bảng cơ sở dữ liệu quan hệ hoặc hệ thống thông tin địa lý.
Mặc dù XSLT được thiết kế như một ngôn ngữ có mục đích đặc biệt để chuyển đổi XML, ngôn ngữ này hoàn thành, khiến nó có khả năng về mặt lý thuyết về các tính toán tùy ý.
Hãy cùng xem cách sử dụng XSLT để chuyển đổi các tài liệu XML thành HTML.
Điều kiện tiên quyết
Eclipse 2020-06, ít nhất Java 1.8, kiến thức về HTML & XML
Thiết lập dự án
Tạo dự án dựa trên Gradle hoặc Maven trong Eclipse. Tên của dự án là Java-XSLT-XML-TO-HTML.java-xslt-xml-to-html.
Nếu bạn đang tạo dự án dựa trên Gradle trong Eclipse thì bạn có thể sử dụng tập lệnh Build.Gradle bên dưới:build.gradle script:
plugins { id 'java-library' } sourceCompatibility = 12 targetCompatibility = 12 repositories { jcenter() } dependencies { }Nếu bạn đang tạo dự án dựa trên maven thì bạn có thể sử dụng tệp pom.xml bên dưới:pom.xml file:
<project xmlns="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.roytuts</groupId> <artifactId>java-xslt-xml-to-html</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>at least 1.8</java.version> </properties> <dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>Tệp XML
Bây giờ đặt tệp XML dưới đây books.xml trong thư mục src/main/resources/xml.
Trong tệp XML dưới đây, bạn có thể thấy chúng tôi có rất nhiều dữ liệu có thể dễ dàng hiển thị trên tệp HTML ở định dạng bảng.
Ở đây chúng tôi có danh mục nút gốc và dưới đây, chúng tôi có một số nút sách. Chúng tôi có ID sách là một thuộc tính trên nút sách. Chúng ta cũng sẽ xem cách trích xuất thuộc tính ID này bằng XSLT.
<?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML. </description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. </description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society. </description> </book> <book id="bk104"> <author>Corets, Eva</author> <title>Oberon's Legacy</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-03-10</publish_date> <description>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. </description> </book> <book id="bk105"> <author>Corets, Eva</author> <title>The Sundered Grail</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-09-10</publish_date> <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy. </description> </book> <book id="bk106"> <author>Randall, Cynthia</author> <title>Lover Birds</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-09-02</publish_date> <description>When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled. </description> </book> <book id="bk107"> <author>Thurman, Paula</author> <title>Splish Splash</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-11-02</publish_date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea. </description> </book> <book id="bk108"> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <genre>Horror</genre> <price>4.95</price> <publish_date>2000-12-06</publish_date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects. </description> </book> <book id="bk109"> <author>Kress, Peter</author> <title>Paradox Lost</title> <genre>Science Fiction</genre> <price>6.95</price> <publish_date>2000-11-02</publish_date> <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum. </description> </book> <book id="bk110"> <author>O'Brien, Tim</author> <title>Microsoft .NET: The Programming Bible</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-09</publish_date> <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference. </description> </book> <book id="bk111"> <author>O'Brien, Tim</author> <title>MSXML3: A Comprehensive Guide</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-01</publish_date> <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more. </description> </book> <book id="bk112"> <author>Galos, Mike</author> <title>Visual Studio 7: A Comprehensive Guide</title> <genre>Computer</genre> <price>49.95</price> <publish_date>2001-04-16</publish_date> <description>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. </description> </book> </catalog>Tệp XSLT
Tiếp theo, hãy tạo tệp XSLT có tên Xslt2Html.xsl và đặt nó trong thư mục src/main/resources/xslt.
Ở đây định dạng tiêu chuẩn của XSLT là giữ mọi thứ bên trong thẻ <xsl:stylesheet/>. Bạn cũng cần chỉ định không gian tên <project xmlns="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.roytuts</groupId> <artifactId>java-xslt-xml-to-html</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>at least 1.8</java.version> </properties> <dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>0 cho XSLT. Sau đó, chúng tôi có thẻ <project xmlns="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.roytuts</groupId> <artifactId>java-xslt-xml-to-html</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>at least 1.8</java.version> </properties> <dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>1 phù hợp với danh mục nút gốc và bắt đầu xử lý từ nút gốc này.
Tiếp theo, chúng tôi muốn chọn dữ liệu XML và hiển thị vào định dạng HTML. Đó là lý do tại sao chúng tôi đã sử dụng thẻ HTML ở đây. Chúng tôi cũng đã sử dụng một số CSS để tạo kiểu dữ liệu hàng thay thế. Sau đó, chúng tôi đang lặp lại từng nút (sách) và chọn các giá trị.
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="//www.w3.org/1999/XSL/Transform"> <xsl:template match="/catalog"> <html> <head> <style> 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) { background-color: #dddddd; } </style> </head> <body> <h2>Books</h2> <table> <tr> <th>Id</th> <th>Author</th> <th>Title</th> <th>Genre</th> <th>Price</th> <th>Publish Date</th> <th>Description</th> </tr> <xsl:for-each select="book"> <tr> <td> <xsl:value-of select="book/@id" /> </td> <td> <xsl:value-of select="author" /> </td> <td> <xsl:value-of select="title" /> </td> <td> <xsl:value-of select="genre" /> </td> <td> <xsl:value-of select="price" /> </td> <td> <xsl:value-of select="publish_date" /> </td> <td> <xsl:value-of select="description" /> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>Biến đổi XML thành HTML
Viết lớp Java để chuyển đổi dữ liệu tệp XML thành HTML bằng tệp XSLT. Chúng tôi đã đặt cả hai tệp XML và XSLT dưới ClassPath và Finaly chuyển đổi dữ liệu XML thành đầu ra HTML. Chúng tôi viết đầu ra vào tệp HTML có tên <project xmlns="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.roytuts</groupId> <artifactId>java-xslt-xml-to-html</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>at least 1.8</java.version> </properties> <dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>2 trong thư mục gốc của dự án.
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(); } }Kiểm tra ứng dụng
Chạy lớp chính ở trên, bạn sẽ tìm thấy tệp sách.html trong thư mục gốc của dự án.books.html file under the project’s root directory.
Bây giờ hãy mở tập tin sách.html trong trình duyệt web trong Eclipse. Bạn sẽ thấy dữ liệu XML cuối cùng ở định dạng bảng trên trình duyệt web Eclipse. Bạn cũng có thể mở tệp HTML đầu ra trong trình duyệt.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.
Mã nguồn
Tải xuống
Cảm ơn vì đã đọc.