XSL (eXtensible Stylesheet Language) 이란?


XML 문서를 presentation 해주기 위한 포맷팅 언어.

xml 문서이다.

1. XSL 의 구성

1) XSLT ( XSL Transformation )
   : xml 문서의 구조를 다른 구조로 변환하기 위한 마크업 언어.
2) XPath ( XSL Path Language )
   : xml 문서 내에서 특정 part (엘리먼트 or 속성)을 찾아가기 위한 경로 표기 언어.
3) XSL-FO ( XSL Formatting Objects )
   : Formatter 프로그램을 통해 XML 문서를 비 XML 문서로 변환하기 위한 마크업 언어.


2. XSL 처리 과정

▪ Transformation : XML 문서를 다른 구조의 XML 문서로 구조를 변환하는 과정.
▪ Formatting       : XML 문서를 특정 S/W, H/W에 맞는 비 XML 문서로 변환하는 과정.

사용자 삽입 이미지

XSL Transform 의 결과물은 파일 형태의 문서가 아닌, 메모리 상에서 트리를 이루는 DOM 객체들로 생성된다. 이것을 Result Tree 라 한다.

3. XSLT 문서의 구성

▪ XML 선언 (optional)
▪ XSLT stylesheet 선언
▪ Top-level element
▪ Template과 Literal result element



◆ XSL 문서의 루트 엘리먼트와 최상위 엘리먼트

1. Root Element
: stylesheet or transform

 

<?xml version="1.0" encoding="euc-kr"?>                

<xsl:stylesheet

version="1.0"                          

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 

</xsl:stylesheet>


▪ version 필수 선언.
http://www.w3.org/1999/XSL/Transform : XSLT 1.0 의 public namespace URI
  cf. http://www.w3.org/1999/TR/WD-xsl  :  XSLT 1.0 공식 권고안이 나오기 이전 MS에서 사용하던 것.

2. Top-level Element
: 루트 엘리먼트의 자식 엘리먼트

-  xsl 문서의 결합
▪  import 엘리먼트
▪  include 엘리먼트


- result tree 문서 종류 결정
▪ output 엘리먼트

- result tree의 엘리먼트 내용을 담고 있는 Top-level Element
▪ template 엘리먼트

- 기타
▪ strip-space 엘리먼트
▪ preserve-space 엘리먼트
▪ key 엘리먼트
▪ decimal-format 엘리먼트
▪ namespace-alias 엘리먼트
▪ attribute-set 엘리먼트
▪ variable 엘리먼트
▪ param 엘리먼트





◆ output 엘리먼트

: Result Tree 의 문서 종류를 지정한다.
  생략되었거나, 있어도 method 속성이 없으면
  default 값은 xml이다.
  ( result tree 의 root element 이름이 namespace 접두사가 없는 'html'일 경우에만 default 값이 'html' )

<xsl:output 속성명="속성값" 속성명="속성값"/>

ex.
<xsl:output method="xml" version="1.0" encoding="euc-kr" indent="yes"/>



속 성 명

  

속성값 유형

method

Result tree 문서 종류 지정

xml, html, text

version

Result tree XML 문서일 경우 XML 권고안 버전

1.0

encoding

Result tree의 인코딩 방식 지정

String(ex:euc-kr,UTF-8)

omit-xml-declaration

Result tree XML 선언 생략 여부.
출력 방법이 'xml'이면 default는 'no'

yes, no

standalone

Result tree의 외부 문서 참조 여부

yes, no

doctype-public

Result tree가 문서 유형 선언을 포함할 경우 PUBLIC 식별자 지정

String

doctype-system

Result tree 가 문서 유형 선언을 포함할 경우 SYSTEM 식별자 지정

String

cdata-section-elements

Result tree에서 CDATA 섹션으로 사용되어야 할 노드 지정
method="xml" 인 경우만 해당.

Qname

indent

Result tree에 화이트스페이스(태그와 태그 사이의 공백)를 포함할 지 여부

yes, no

media-type

media-type 지정

String



사용자 삽입 이미지















 

◆ 노드 및 노드셋


XML 문서

<?xml version=”1.0”>

<musiclist>

     <title>사랑 하나면 돼</title>

<title>착한 거짓말</title>

<title>물끄러미</title>

</musiclist>

루트 노드 : 문서 자체를 뜻하는 노드

 

루트 엘리먼트 노드

title  

    title     노드 셋 : 같은 엘리먼트 이름을 가진 노드들.

    title                   

 

 




Template Rule


어떤 구조를 다른 구조로 바꾸는 방법.

▪ 원본 XML 문서의 노드(엘리먼트)들을 다른 구조의 노드(엘리먼트)로 바꾸는 역할.


1. 정의
==============================================================================================


<xsl:template match="pattern">   

             <!-- Content: (xsl:param*, template) -->

</xsl:template>

ex.

        <xsl:template match="//book">       ← XSLT 엔진이 소스 트리에서 <book> 엘리먼트 발견할    

             .....                                            때마다 처리한다. node-set에 템플릿 룰을 적용해 변환.

        </xsl:template>


▪ match 속성 : 소스 트리의 하나의 패턴을 규정한다.
                     패턴에 매치하는 어떤 노드에도 적용될 수 있다.

▪ pattern : XML 문서에서 변환되어야 할 대상 노드 지정.

              Xpath 표현식 중, 한 개 노드 or 노드셋을 가리키는 표현식.

   

   

/

루트 노드(문서 자체) 지정.

/노드명/…/노드명

특정 경로의 노드() 지정.

//노드명 or 노드명

경로 상관없이 같은 이름의 노드() 지정.

/노드명/노드명[@속성명=’속성값’]

특정 속성값을 가지는 노드() 지정.

/노드명/노드명[@속성명!=’속성값’]

특정 속성값과 다른 속성값을 가지는 노드() 지정.


▪ Xpath expression Vs Xpath pattern

)  /name/first


1) Xpath express : document root 로 가서 <name> 자식 요소를 찾은 후, <first> 자식 요소로 가라
2) Xpath pattern  : <name> 요소의 한 자식인 어떤 <first> 요소와 일치시켜라. 이것은 document root 의 자식이어야 한다.



2. 적용

==============================================================================================
: 템플릿 룰을 통해 변환된 result tree의 어떤 부분에 포함할 것인지 알려준다.
 
 

<xsl:apply-templates select="node-set-expression">

              <!-- Content: (xsl:sort | xsl:with-param)* -->
<xsl:apply-templates>

ex. <xsl:apply-templates select="book">


▪ select 속성 : 모든 children을 처리하는 대신 선택된 노드만 처리한다.

▪ XSL 변환기의 동작

① select 속성에 지정된 노드와 동일한 노드를 match 속성으로 갖는 템플릿 룰을 찾는다.
② 템플릿 룰을 적용해 변환된 내용을 xsl:apply-templates 엘리먼트와 대치시킨다.

③ select 속성 생략시, 모든 템플릿 룰을 적용해 변환된 내용을 xsl:apply-templates 엘리먼트와 대치시킨다.


3. name 속성
==============================================================================================
: XSL 문서내에서 반복 적용되는 내용을 한 개의 템플릿 룰로 만들고,

  그 템플릿 룰명으로 다른 템플릿 룰에서 참조해서 적용할 경우에 사용된다.
 
템플릿 룰은 match와 name 속성 중 하나를 반드시 기술해야 한다.

1) 정의

<xsl:template name="Template Rule name">

                   <!-- Content: (xsl:param*, template) -->

</xsl:template>


ex.

<xsl:template name="tYear">

         <font color="red">2007년</font>
</xsl:template>  


2) 적용

<xsl:call-template name="Template Rule name">

             <!-- Content: xsl:with-param* -->
<xsl:call-template/>

ex. <xsl:call-template name="tCompany"/>



4. priority 속성
==============================================================================================
: XML 문서의 대상 노드를 변환시키는 템플릿 룰이 여러 개 있을 경우 우선선위가 높은 템플릿 룰이 적용되도록 한다.

priority number 가 클 수록 우선순위가 높다.

name 속성을 갖는 template rule 에서는 사용할 수 없다.


<xsl:template match="pattern" priority="number”>

         <!-- Content: (xsl:param*, template) -->
</xsl:template>


ex.

<xsl:template match="musiclist" priority="1”>

<th>title</th>

</xsl:template>

 

<xsl:template match="/musiclist /music" priority="2">

<th>price</th>

</xsl:template>



5. mode 속성
==============================================================================================
: 소스 트리의 같은 부분이 한 번 이상 처리되어야 할 때 사용한다.
name 속성을 갖는 template rule 에서는 사용할 수 없다.  (match 속성만 가능)

1) 정의

<xsl:template match="pattern" mode="Mode Name">

             <!-- Content: (xsl:param*, template) -->

</xsl:template>


ex.

<xsl:template match="title" mode="modeA">

               <xsl:value-of select="author"/>

</xsl:template>


2) 적용

<xsl:apply-templates select="node-set-expression" mode="Mode Name"/>


ex.
<xsl:apply-templates select="/musiclist/title[@genre=
jazz']" mode="modeA"/>

<xsl:apply-templates select="/musiclist/title[@genre=dance']" mode="modeB"/>





◆ XML 문서의 내용 가져오기


1. 엘리먼트의 컨텐트 내용 or 속성값 가져오기 : value-of

==============================================================================================

1) 엘리먼트의 컨텐트 내용 가져오기

<xsl:template match="대상 노드">

               <xsl:value-of select="대상 노드 자신 or 자식 노드명"
                                 disable-output-escaping="yes or no"/>

</xsl:template>

ex.
<xsl:template match="/musiclist/music">

               <xsl:value-of select="."/>          // title 노드 자신의 컨텐트 내용을 가져와 대치한다.

</xsl:template>


<!-- 컨텐트 내용이 숫자일 경우 -->
<xsl:template match="/musiclist/music">

               <xsl:value-of select="format-number(price, '###,###')"/>         
</xsl:template>



2) 속성값 가져오기

<xsl:template match="대상 노드">

               <xsl:value-of select="@속성명"/>

</xsl:template>

ex.
<xsl:template match="/musiclist/music">

               <xsl:value-of select="@genre"/>        
</xsl:template>


disable-output-escaping 속성
: XSLT processor 에게 이스케이프 문자 ("&amp;", "&lt;") 대신 "&", "<" 문자를 출력하라고 지시한다.
  default는 'no' 로, 보통은 XSLT processor가 출력시 자동으로 이런 문자로 바꾸어준다.
  xsl:value-of 와 xsl:text 엘리먼트의 속성으로 사용된다.

ex. <name>&amp;</name>

<xsl:value-of select="name" disable-output-escaping="yes"/>

→ 결과는 &

<xsl:value-of select="name" disable-output-escaping="no"/>

→ 결과는 &amp;




2. 엘리먼트 or 속성 복사해서 가져오기 : copy-of
==============================================================================================
: 원본 XML 문서의 일부분을 구조 변경 없이 복사해서 변환될 XML 문서에 붙인다.

<xsl:template match="대상 노드">

               <xsl:copy-of select="(복사할)자식노드명 or @속성명"/>

</xsl:template>

ex.

<xsl:template match="music">

               <xsl:copy-of select="title"/>

               <xsl:copy-of select="@genre"/>
</xsl:template>



◆ 정렬 (Sort)

<xsl:apply-templates select="대상 노드">

        <xsl:sort select="자식노드명 or @속성명"
                     data-type="number | text"
                     order="ascending | descending"
                     case-order="upper-first | lower-first"/>

</xsl:apply-templates>


ex.

<xsl:apply-templates select="/musiclist/music">

          <xsl:sort select="price" data-type="number" order="ascending"/>

</xsl:apply-templates>


default
   data-type : text
   order : ascending
   case-order : document에 사용되는 언어를 정의하는 lang 속성에 의존.
                     (upper-first일 경우 "A B a b" -> "A a B b")
▪ xsl:apply-templates 엘리먼트와 xsl:for-each 엘리먼트의 자식엘리먼트로 작성된다.

▪ 2차 정렬
: 1차로 컬럼을 먼저 정렬시키고, 정렬된 상태에서 다른 컬럼을 2차로 정렬시키는 것.

<xsl:apply-templates select="/musiclist/music">

              <!-- 1차 정렬 -->

              <xsl:sort select="@genre"/>

              <!-- 2차 정렬 -->

              <xsl:sort select="price" data-type="number" order="ascending"/>

</xsl:apply-templates>





◆ 번호 매기기

: XSL 변환기는 result tree 생성시 자동으로 번호를 매겨 삽입할 수 있다.
  이 기능을 이용해 XSL 문서에서 번호가 삽입되는 위치에 xsl:number 엘리먼트를 작성한다.

<xsl:template match="대상 노드">
              <xsl:number format="
번호 형식">
</xsl:template>

ex.
<xsl:template match="music">
   <tr>
      <td><xsl:number format="1"></td>
      <td><xsl:value-of select="title"></td>
   </tr>             
</xsl:template>


번호 형식 : '1', 'a', 'A', 'i', 'I', '(1)'




◆ 제어 엘리먼트


1. xsl:if 엘리먼트
==============================================================================================
: 조건식이 참이면 변환 내용을 적용한다.

<xsl:template match="xml 대상 노드">

        <xsl:if test="조건식">

                   <!-- Content: template -->
     
</xsl:if>

</xsl:template>


▪ 조건식에 자주 오는 XPath 표현식

조건식

설명

노드명=’문자열

컨텐트 내용이 문자열을 가지면 참

@속성명=’속성값

주어진 속성값을 가지면 참

@속성명!=’속성값

주어진 속성값이 아닌 다른 값을 가지면 참

start-with(노드명,’문자열’)

컨텐트 내용이 문자열로 시작하면 참

contains(노드명,’문자열’)

컨텐트 내용이 문자열을 포함하면 참




2. xsl:choose 엘리먼트
==============================================================================================

<xsl:template match="music">
     
<xsl:choose>
           
<xsl:when test="조건식1">       

                  <!-- Content: template -->
           
</xsl:when>

                           
           
<xsl:when test="조건식2">

                  <!-- Content: template -->           
            </xsl:when>

                         
           
<xsl:otherwise>                    <!-- 생략 가능 -->

                   <!-- Content: template -->
           
</xsl:otherwise>
     
</xsl:choose>

</xsl:template>

test 표현 중 하나라도 참이 되면 <xsl:choose>를 빠져나간다.


3. xsl:for-each 엘리먼트
==============================================================================================
: 대상 노드 숫자만큼 반복해서 변환시킨다.
  반드시 템플릿 룰 안에서 작성되어야 한다.

<xsl:template match="대상 노드">

     <xsl:for-each select="대상 노드">

       변환 내용
     </xsl:for-each>
</xsl:template>


ex.
<xsl:for-each select="/musiclist/music">

<tr>

<td><xsl:value-of select="title"/></td>

<td><xsl:value-of select="@genre"/></td>

</tr>

</xsl:for-each>





◆ 변수와 파라미터


1. 변수
==============================================================================================

1) 변수 선언

<xsl:variable name="변수명" select="변수값"/> 

<xsl:variable name="변수명">변수명</xsl:variable>

<!-- 변수값으로 빈 문자값을 줄 경우 -->
<xsl:variable name="변수명" select="''"/> 
<xsl:variable name="변수명"/>

ex.

<xsl:variable name="vList" select="'책목록'"/>  <!--select 속성값 지정시, 문자열인 경우 반드시 ''-->

<xsl:variable name="vKind">
       <!-- Content: template -->
</xsl:variable>



2) 변수 사용
▪ 변수값(=단순한 문자열) & result tree의 컨텐트 내용으로 사용될 경우

<엘리먼트> <xsl:value-of select="$변수명"/> </엘리먼트>

ex.
  <xsl:template match="music">
             <xsl:value-of select="$변수명"/>
      </xsl:template>


▪ 변수값(=단순한 문자열) & result tree의 속성값으로 사용될 경우

속성명="{$변수명}"

ex.
<font size="{$vGenre}"> .... </font>


▪ 변수값(=단순한 문자열) & XPath 표현식에서 사용될 경우

[노드명=$변수명] or [@속성명=$변수명]

ex.
<xsl:for-each select="//music[@genre=$vGenre]">


▪ 변수값이 result tree의 일부분을 이루는 엘리먼트들로 구성되어 있을 경우

<엘리먼트> <xsl:copy-of select="$변수명"/> </엘리먼트>

ex. <xsl:copy-of select="$vSize"/>



3) 변수 사용 범위
▪ global variable : top-level Element 로 작성. Template Rule 위에 작성해도 좋고, 아래에 작성해도 좋다.
▪ local variable : Template Rule 내에서 작성


4) 변수 예제
▪ xml 예제

more..


▪ xsl 예제

<?xml version="1.0" encoding="euc-kr"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 

 <!-- 글로벌 변수 선언  -->

 <xsl:variable name="vList" select="'쇼핑목록'"/>

 <xsl:variable name="vKind">computer</xsl:variable>

 <xsl:variable name="vSize" select="10"/>

 <xsl:variable name="vCompany">

       <font color="blue">Cheap</font> Company
 </xsl:variable>

 

 <!-- 시작 템플릿   -->

 <xsl:template match="/">

    <html>

       <body>

          <!-- 컨텐트 내용으로 사용  -->

          <h2><xsl:value-of select="$vList"/></h2> 

                   

          <!-- XPath 표현식에서 사용 -->

          <xsl:for-each select="//product[@kind=$vKind]">

                          

             <!-- 속성값으로 사용  -->

             <font size="{$vSize}"> 

                 <xsl:value-of select="title"/>

             </font>

             <br/>

          </xsl:for-each>

                   

           <!-- result tree 일부분을 이루는 엘리먼트로 구성될 변수값 사용 -->

          <xsl:copy-of select="$vCompany"/>

       </body>

</html>

</xsl:template>

</xsl:stylesheet>


▪ 결과
사용자 삽입 이미지

▪ <xsl:copy-of select="$vCompany"/> → <xsl:value-of select="$vCompany"/> 로 변경하면
font가 적용되지 않고 텍스트만 결과로 출력된다.


2. 파라미터
==============================================================================================

: 현재 템플릿 룰에서 다른 템플릿 룰을 적용할 때 전달하고 싶은 데이터가 있을 경우

1) 파라미터 선언

<xsl:param name="파라미터명" select="파라미터값"/> 

<!-- 파라미터값으로 빈 문자값을 줄 경우 -->
<xsl:param name="파라미터명" select="''"/> 
<xsl:param name="파라미터명"/>


2) 파라미터 전달

▪ xsl:with-param 엘리먼트는 xsl:apply-templates엘리먼트와 xsl:call-template 엘리먼트의 자식 엘리먼트로 작성된다.

▪ select 속성값으로 엘리먼트 노드, 텍스트 노드 모두 가능하다.
  또한 꼭 소스 트리에서 올 필요는 없고, 문자열을 넘겨도 좋다.
  ex. 엘리먼트 노드일 때 : <xsl:with-param name="pTitle" select="title"/>
        텍스트 노드일 때   : <xsl:with-param name="pTitle" select="title/text()"/>
        문자열일 때           : <xsl:with-param name="pTitle" select="'문자열 파라미터이다'"/>
   
▪ xsl:apply-templates엘리먼트 : match 속성 갖는 다른 템플릿 룰을 적용
<xsl:apply-templates match="대상 노드">
        <xsl:with-param name="파라미터명" select="전달할 데이터"/>
</
xsl:apply-templates>


▪ xsl:call-templates엘리먼트   : name 속성 갖는 다른 템플릿 룰을 적용

<xsl:call-template name="Template Rule name">
        <xsl:with-param name="파라미터명" select="전달할 데이터"/>
</
xsl:apply-template>


3) 파라미터 사용

<xsl:template ~>
       <!-- 파라미터 선언 -->
      <xsl:param name="파라미터명"/>
       <!-- 파라미터 사용 -->
         .....
<xsl:template>


4) 예제

<xsl:template match="book">

          <!-- 파라미터 값 전달 -->

          <xsl:call-template name="tBook">

                  <xsl:with-param name="pTitle" select="title"/>

          </xsl:call-template>

</xsl:template>

 

<xsl:template name="tBook">

          <!-- 파라미터 선언 -->

          <xsl:param name="pTitle"/>   
         
<!-- 파라미터 사용 -->       
         
<xsl:value-of select="$pTitle"/>

</xsl:template>





◆ XSL 문서의 결합

: 외부 XSL 문서를 참조

1. xsl:include 엘리먼트
==============================================================================================
: Top-level 엘리먼트로서 작성된다.
  다른 Top-level 엘리먼트 (ex. Template Rule) 의 정의가 앞이나 뒤에 있어도 상관 없다.
<xsl:include href="uri-reference"/>



2. xsl:import 엘리먼트
==============================================================================================
: 다른 Top-level 엘리먼트보다 먼저 작성되어야 한다.
  여러 개 작성할 수 있다.

<xsl:import href="uri-reference"/>


▪ 참조하는 문서와 참조되는 문서에 같은 match 속성값이 정의되어 있을 경우,
  참조하는 XSL 문서의 Template Rule 이 적용된다.


글 보관함

카운터

Total : / Today : / Yesterday :
get rsstistory!