XPath

개념


XPath는 W3C 표준으로 XML 문서에서 노드를 탐색하고 조회하기 위한 기술이며 XSLT의 핵심 기반입니다. XSLT의 select="", test="" 내부 표현식은 전부 XPath를 사용합니다.

  • 경로 표현식으로 노드를 찾음
  • 문자열, 숫자, 날짜 비교, 노드 처리, 논리 연산 등 100개 이상의 내장 표준 함수 제공

7가지 노드 유형

문서 노드(루트 노드), 요소 노드, 속성 노드, 텍스트 노드, 주석 노드, 처리 명령 노드, 네임스페이스 노드.

예시:<title lang="eng">Harry Potter</title>

  • <title> → 요소 노드
  • lang="eng" → 속성 노드
  • Harry Potter → 텍스트 노드

개념

  1. 원자 값(Atomic value):자식도 부모도 없는 노드 내용,예:eng29.99
  2. 아이템(Item):아이템 = 노드 또는 원자 값

XML 노드 간 관계

<bookstore><book><title></title></book></bookstore> 를 예시로

  1. 부모(Parent):모든 요소와 속성은 부모가 하나만 존재;booktitle의 부모 노드
  2. 자식(Children):요소는 여러 자식 노드를 가질 수 있음;titlepricebook의 자식 노드
  3. 형제(Sibling)동일한 부모 노드를 가짐;같은 레벨의 title, price는 서로 형제 노드
  4. 조상(Ancestor):부모, 부모의 부모 등 상위 모든 노드;title의 조상:book, bookstore

경로 표현식

경로와 단계를 이용하여 XML 노드를 선택

<bookstore>
  <book>
    <title lang="eng">Harry Potter</title>
    <price>29.99</price>
  </book>
</bookstore>Code language: HTML, XML (xml)
표현식의미
bookstore루트 아래 bookstore 요소 선택
/bookstore절대 경로, 루트 노드부터 매칭
bookstore/bookbookstore 하위 모든 book 자식 요소 선택
//book문서 전체 영역의 book 요소(전역 검색)
//@lang이름이 lang인 속성 노드 전부 선택

XPath 함수:position()

<xsl:value-of select="position()" />Code language: HTML, XML (xml)

position()은 XPath 내장 함수로 노드 집합에서 현재 순회 중인 노드의 일련번호를 가져오며 1부터 카운트합니다.

예시,일련번호 출력

<?xml version="1.0" encoding="gb2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head></head>
<body>
<ul>
    <!--모든 학생 class/student 순회 -->
    <xsl:for-each select="class/student">
        <xsl:sort select="age"/>  <!--나이 오름차순 정렬-->
        <!--키>160 학생 필터링-->
        <xsl:if test="height &gt; 160">
            <li>
                <xsl:value-of select="position()" /><!--일련번호 출력-->
                <xsl:value-of select="name"/><!--다중 조건 분기-->
                <xsl:choose>
                    <xsl:when test="height &gt; 200">
                        <b><xsl:value-of select="age"/></b>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="age"/>
                    </xsl:otherwise>
                </xsl:choose>
            </li>
        </xsl:if>
    </xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Code language: HTML, XML (xml)

XPath

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다