Coding/etc

[XSLT 예제] 다중 조건문 수행하기

junedev 2019. 9. 9. 16:46

Question


편의점 알바인 라이언은 매일 창고 재고목록을 파악하고 남은 수량이 30개보다 적은 상품은 주문 발주를 넣습니다. 다음 창고 재고목록표를 보고 라이언이 발주를 넣어야 할 상품과 그렇지 않은 상품을 구분하여 출력하세요.

(*XSLT 다중조건문(xsl:choose)을 활용하기)

 


기대 결과

 


xml파일 실행 시 다음과 같은 화면이 출력되어야 합니다.



 

지난 포스팅에서 다뤘던

2019/09/06 - [Coding/XML] - [XSLT 예제] 간단한 조건문 처리하기

 

[XSLT 예제] 간단한 조건문 처리하기

Question 편의점 알바인 라이언은 매일 창고 재고목록을 파악하고 남은 수량이 30개보다 적은 상품은 주문 발주를 넣습니다. 다음 창고 재고목록표를 보고 라이언이 발주를 넣어야 할 상품 목록을 출력하세요. (*X..

enfanthoon.tistory.com

에서 조금 더 복잡한 다중 조건문을 다루어 보도록 하겠습니다.

문제와 데이터 샘플은 지난 포스팅과 비슷하지만, 차이점이라면 이번에는 xsl:choose를 사용하여

조건문이 충족할 경우와 아닌 경우를 구분하여 실행시켜 보도록 하겠습니다.

기본적으로 데이터 샘플은 지난번과 같이 위의 테이블을 이용하면 되겠습니다.

 

<product.xml>

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="xslt_choose.xsl"?>
<products_list>
  <product>
    <name>당근</name>
    <category>vegetable</category>
    <amount>55</amount>
  </product>
  <product>
    <name>복숭아</name>
    <category>fruit</category>
    <amount>40</amount>
  </product>
  <product>
    <name>우유</name>
    <category>dairyproduct</category>
    <amount>25</amount>
  </product>
  <product>
    <name>사과</name>
    <category>fruit</category>
    <amount>15</amount>
  </product>
  <product>
    <name>자두</name>
    <category>fruit</category>
    <amount>35</amount>
  </product>
  <product>
    <name>요거트</name>
    <category>dairyproduct</category>
    <amount>60</amount>
  </product>
  <product>
    <name>오이</name>
    <category>vegetable</category>
    <amount>10</amount>
  </product>
</products_list>

(href 요소만 이번 예제의 파일명 xslt_choose.xsl로 바꿔줍시다)

 

 

<xsl:choose>요소는 <xsl:when>과 <xsl:otherwise>요소와 함께 다중 조건문을 작성할 때 사용합니다.

<xsl:when>요소는 test 속성으로 전달받은 표현식이 참인 경우에만 실행된다고 지난 포스팅에서 다뤘죠?

전달받은 표현식이 거짓인 경우에는 <xsl:when>요소는 실행되지 않으며, 대신에 <xsl:otherwise>요소가 실행됩니다.

쉽게말해 If문, Else문의 역할을 수행한다고 보면 됩니다.

 

<xslt_choose.xml>

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">

    <html>
      <body>
        <h2 style="text-align:center">상품 발주</h2>
        <xsl:for-each select="products_list/product">
          <xsl:choose>
            <xsl:when test="amount &lt; 30">
              <xsl:value-of select="name"/> : 주문해야 할 상품<br/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="name"/> : 주문하지 않아도 되는 상품<br/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

 

 

다중 조건문을 위해 <xsl:choose> 요소를 작성하고,

조건식 "amount &lt; 30" (amount 요소가 30보다 작을 때)가 충족할 경우

주문해야 할 상품이라고 출력하고,

그 밖의 경우는 xsl:otherwise 요소를 통하여 처리해 줍니다.

배운 대로 적용해보면, amount 요소가 30보다 작다면 주문해야 할 상품이라고 표시되고,

반대의 경우 주문하지 않아도 되는 상품이라고 표시되겠네요.

 

그 외 요소는 이전 포스팅에서 자세히 다루었으니 참고하시길 바랍니다.

 

 

xslt_choose.xsl
0.00MB