JSTL(JSP Standard Tag Library)의 XML 태그 라이브러리에 포함된 <x:transform> 태그는 XML 문서에 XSLT(XSL Transformation) 변환을 적용합니다. 이 태그를 활용하면 원본 XML 데이터를 별도의 자바 코드 작성 없이도 원하는 형태의 HTML이나 다른 구조의 문서로 손쉽게 변환할 수 있습니다.
<x:transform> 태그의 주요 속성
<x:transform> 태그에서 사용할 수 있는 속성은 다음과 같습니다.
| 속성 | 설명 | 필수 여부 | 기본값 |
|---|---|---|---|
| doc | XSLT 변환의 대상이 되는 원본 XML 문서 | 아니요 | 태그 본문(Body) |
| docSystemId | 원본 XML 문서의 URI | 아니요 | 없음 |
| xslt | 변환 지침을 담고 있는 XSLT 스타일시트 | 예 | 없음 |
| xsltSystemId | 원본 XSLT 문서의 URI | 아니요 | 없음 |
| result | 변환 결과를 받아 저장할 결과 객체(javax.xml.transform.Result) | 아니요 | 페이지에 직접 출력 |
| var | 변환된 XML 문서가 저장되는 변수 이름 | 아니요 | 페이지에 직접 출력 |
| scope | 변환 결과를 노출할 변수의 유효 범위(scope) | 아니요 | 없음 |
사용 예제
먼저 다음과 같은 XSLT 스타일시트 style.xsl 파일이 있다고 가정해 보겠습니다. 이 스타일시트는 books 요소를 HTML 테이블 형태로 변환하는 역할을 합니다.
<?xml version = "1.0"?> <xsl:stylesheet xmlns:xsl = "https://www.w3.org/1999/XSL/Transform" version = "1.0"> <xsl:output method = "html" indent = "yes"/> <xsl:template match = "/"> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match = "books"> <table border = "1" width = "100%"> <xsl:for-each select = "book"> <tr> <td> <i><xsl:value-of select = "name"/></i> </td> <td> <xsl:value-of select = "author"/> </td> <td> <xsl:value-of select = "price"/> </td> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet>
이제 위 스타일시트를 적용할 JSP 파일을 살펴보겠습니다. 이 예제에서는 <c:set> 태그로 XML 데이터를 변수에 담고, <c:import> 태그로 외부 스타일시트를 가져온 뒤, <x:transform> 태그로 두 요소를 결합해 변환을 수행합니다.
<%@ taglib prefix = "c" uri = "https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "x" uri = "https://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:transform Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var = "xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
<c:import url = "https://localhost:8080/style.xsl" var = "xslt"/>
<x:transform xml = "${xmltext}" xslt = "${xslt}"/>
</body>
</html>
위 코드를 실행하면 XML 데이터가 스타일시트에 정의된 대로 HTML 테이블로 변환되어 다음과 같은 결과가 화면에 출력됩니다.
실행 결과 – 도서 정보(Books Info)
| Padam History ZARA | 100 |
| Great Mistry NUHA | 2000 |