CodeGym /행동 /Kotlin SELF /DOM wieeui XPath

DOM wieeui XPath

Kotlin SELF
레벨 50, 레슨 2
사용 가능

1. XML-eul 다루는 또 하나의 방법

DOM-eul cheoeum ikhigo nan hueneun ireon neukkimi deumnida: “좋아, 이제 naneun eotteon node-kkaji라도 gal su iteo, teurireul geunyang georeogamyeon dwae.” Ige matseumnida… daeman, yeonseup-yong boda jom deo bokjapan cheoeum XML-eul mannan geu sungan kkajiman. Geu da-eumen jeongmal jeongseok: getElementsByTagNamereul manhi ssego, item(0) gat-eun indekseuga sancheoreom ssahigo, 타이پ 캐스팅, binkabim geomsa — geurigo deiteo ilgineun kodeuga XML jasinboda deo gil-eojimnida.

XPath-neun seontaeg-eul seolmyeongjigeuro (declaratively) hyunpyeonhagi wihae piryohamnida: “id=42인 sayongja ireum jwo”이지, “meonjeo modeun user-reul chatgo, geu daeum hoebalhamyeo, id-reul bigyo하고, geu daeum name-eul kkeunna”ga 아닙니다.

XPath-reul XML teurireul wihan “mini juil eoneo”ro bogo sip-eul su it습니다. Neukkimeuro neun 폴더 ne비게이션 (gyeongro hyeongsik /users/user/name) gwa yusa hajiman, 필터와 “깊이 검색”i it습니다. Geurigo… gakkeum XPath-neun jumuncheoreom bo이지 man, urin 짧고 이해하기 쉬운 jumun-eul sseul geosimnida. 그렇지 않으면 magie-ga tech debt-ro byeonhamnida.

2. XPath-neun DOM wieeeseo dongjakhanda

XPath-reul sseugi jeon, han 가지 jaju saenggineun hon란-eul jeongrihae du-neun geos-i jung요합니다. XPath-neun “daeche API XML parser”ga 아닙니다. oneul uiri jeopgeuneseo XPath-neun teksuteu-reul parsing haji anhseumnida. Meonjeo XML-eul DOM-euro parsinghae Documentreul eodneun hu, geu daeum ime seongryo doen teurireul dae상-euro XPath pyohyeon-eul 실행합니다.

즉, paipraeneun ireohge boimnida:

flowchart LR
    A["XML (String)"] --> B["DOM parse → Document"]
    B --> C["XPath query → value/nodes"]
    C --> D["Kotlin-objekteu (ye: Expense)"]

DOM-eun XML-eul memori sang-ui gujo 로 byeonhwanhaneun yeokhal-eul hago, XPath-neun geu gujo eseo pyeonlihan seontaeg-eul hae 줍니다.

3. XPath mini sajeon: gyeongro, //, sokseong, text()

XPath-neun cheoeum-eun /, //, @, [] gateun 기호-deul ttaemun-e mu섭ge 느껴질 su it습니다. Hajiman uimi로 ppaego bomyeon 꽤 사람다운 논리-ga it습니다. oneuleun “axis”나 고급 기능-kkaji neom-eogaji ango, 실무 코드에서 자주 쓰는 일상 세트만 다루겠습니다.

A래는 작은 치트시트 표입니다. 옆에 두고, 처음부터 외우려 하지 않아도 됩니다 (uriga go대 rune siheom 보는 geosdo 아니니까요).

XPath jogak uimi (개념) yep
/a/b/c
munseo root-eseo buteo-ui gyeongro
/users/user/name
//c
munseo eodideun c chatgi (“깊이 검색”)
//item
@id
hyeonjae node-ui id sokseong
/user/@id
[@id='42']
sokseong-eul gijeon-euro han 필터 (predicate)
//user[@id='42']
text()
teksuteu node (naeyong)
/user/name/text()

nyeok-areul julyeo juneun du 가지 mete:

Cheot째, //neun pyeonlihajiman wiheomhamnida: munseo-ga keugeojigeona gujo-ga bakkwimyeon, saeng각boda deo manheun node-reul chat-eul su it습니다.

Dul째, XPath-neun XML formatting ttaemun-e gongbaek이나 줄바꿈-i 섞인 munjayeol-eul dolyeo-juneun gyeong-u-ga manheun데, geuraeseo trim()eun chingu이지 jeok-i 아닙니다.

4. Kotlineseo XPath junbi mit gibon modeu

Documentwa XPath saengseong

Jigeum-eun choeso한-ui tec “obwijing”: Documentreul eotteohge eodgo, juil-reul 실행할 su inneun XPath 객체-reul eotteohge mandeuneunjireul 짚어봅니다. Igeon 표준 Java API지만 Kotlineseo도 아주 jal bulleojub니다 (oneuljjumeun Java interoperability-reul mu서워하지 않죠).

Kotlin main skel eotten geos-eun iksuk하니, gan단한 예제로 시작합시다: XML parsing → XPath saengseong → gachi kkeunneogi.


import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathFactory

fun main() {
    val xml = """<user id="42"><name>Ann</name></user>"""

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val xPath = XPathFactory.newInstance().newXPath()
    val name = xPath.evaluate("/user/name/text()", doc).trim()

    println(name) // Ann
}

Juim: yeogiseo evaluate(...)ga munjayeol-eul dolyeo jwo-seumnida. Igeon XPath-ui gajang gan-danhan modeu — “gyeolgwa-reul teksuteuro jwo.” Ireongeun ireum, han beon-ui geum-aek, han beon-ui 상태 처럼 jeomjeom seontaeg-e jeoghab합니다.

“munjayeol jwo” modeu: evaluate(expr, doc) wa binnan gyeolgwa

evaluate(...)reul gyeolgwa type eopsi sseumyeon, botong munjayeol-eul 받습니다. Geu daeum silmueseo jung요한 ha-na: node-ga eop-seul ttae nulli 아니라, 빈 문자열i ol 때-ga 많습니다. Igeon bugga 아니라, geu modeu-ui contract 입니다.

XML-eseo “빈 값”과 “아예 못 찾음”을 섞지 않으려면, “String?reul dolyeo jwo” gateun jageun yutiliti-ga pyeonli합니다.

import javax.xml.xpath.XPath

fun xPathTextOrNull(xPath: XPath, expr: String, doc: Any): String? {
    val raw = xPath.evaluate(expr, doc).trim()
    return raw.takeIf { it.isNotEmpty() }
}

sayong yep:

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathFactory

fun main() {
    val xml = """<user id="42"></user>"""
    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val xPath = XPathFactory.newInstance().newXPath()
    val name = xPathTextOrNull(xPath, "/user/name/text()", doc)

    println(name) // null
}

Yeogiseoneun uidojeok-euro “빈 문자열”을 “값 없음”으로 바꿉니다. Ige Kotlineseo logic-eul 훨씬 jeongjik하게 mandeureo 줍니다: null eun “못 찾음”을 jeopgeun적으로 말해 주고, “빈 문자열이 가끔 absence”라는 규칙을 외우게 하지 않습니다.

“node jwo” modeu: NODESET wa NodeList

Han gae 값이 아니라, 여러 개의 유사한 element (yep: shopping list, transaction list, user list)reul kkeunnaeya 하면, munjayeol modeu-neun 부적합합니다. “node set”이 piryohamnida.

Java XPath APIeseoneun XPathConstants.NODESETeul sse고, gyeolgwa type-eun NodeList입니다.

Jung요: NodeListneun Listga 아닙니다. Byeonhwan eopsineun map{} 과 filter{} reul “정상적으로” 쓰기 어렵습니다. Daesin indekseuro 순회할 su it습니다: 0 until nodes.length (네, 또 0부터 시작하는 인덱스입니다). oneul-ui juyo style-i geureoh습니다.

mini yep:

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathFactory
import org.w3c.dom.NodeList

fun main() {
    val xml = """
        <items>
            <item>Milk</item>
            <item>Bread</item>
        </items>
    """.trimIndent()

    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val xPath = XPathFactory.newInstance().newXPath()
    val nodes = xPath.evaluate("//item", doc, XPathConstants.NODESET) as NodeList

    for (i in 0 until nodes.length) {
        println(nodes.item(i).textContent.trim())
        // Milk
        // Bread
    }
}

Kotlin-ui for mun-eun iterator wieeeseo dongjakhajiman, NodeListneun Iterablei 아니어서, uriga yeonhyeong indekseu style-eul sseumnida.

5. XPath-reul sayonghae XML-eseo 지출 importhagi

Jigeum-eun bon-gyeokjigeuro, i gwaje-reul wihan haeg심: 콘솔 app (gageum — 지출 tracker) 에 XML-eseo 지출-eul kkeunnaoneun 기능eul chuga합시다. Naljja/통화-neun bokjaphage haji 않겠습니다: geum-aek-eun Double, kategori 와 note-neun munjayeol-ro 둡니다. XML-eun gan단하지만 현실-gwa yusa한 hyeongsik-eul sse겠습니다.

deiteo model

Gan결한 Expense model-eul mandeulja. Silje projecteseoneun deo 풍부할 su 있지만, oneul-eun import-ga haeg심입니다.

data class Expense(
    val amount: Double,
    val category: String,
    val note: String
)

importhal XML

val xml = """
    <expenses>
        <expense category="food">
            <amount>12.50</amount>
            <note>Lunch</note>
        </expense>
        <expense category="transport">
            <amount>2.75</amount>
            <note>Bus</note>
        </expense>
    </expenses>
""".trimIndent()

munjayeol-eul Documentro parsing

함수는 짧게: han 가지 책임 — DOM-eul 얻기.

import javax.xml.parsers.DocumentBuilderFactory
import org.w3c.dom.Document

fun parseXml(xml: String): Document =
    DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

XPath-ro <expense> node seontaeg

Yeogiseo XPath-neun <expense ...>...</expense> element moglog-eul dolyeo줍니다.

import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathFactory
import org.w3c.dom.Document
import org.w3c.dom.NodeList

fun selectExpenseNodes(doc: Document): NodeList {
    val xPath = XPathFactory.newInstance().newXPath()
    return xPath.evaluate("/expenses/expense", doc, XPathConstants.NODESET) as NodeList
}

NodeListreul List<Expense>로 바꾸기

Yeogiseo-ga XML segye와 Kotlin segye sa-i-ui “bridge”입니다.

Juim: sokseong categorywa teksuteu amount/notereul 읽습니다. amountneun toDoubleOrNull()ro 안전하게 parse합니다 — deiteo-ga “이상”할 su it고, 한 글자 ttaemun-e kodeuga down되면 안 되니까요.

import org.w3c.dom.Element
import org.w3c.dom.NodeList

fun parseExpenses(nodes: NodeList): List<Expense> {
    val result = mutableListOf<Expense>()

    for (i in 0 until nodes.length) {
        val el = nodes.item(i) as Element
        val category = el.getAttribute("category").trim()
        val amount = el.getElementsByTagName("amount")
            .item(0).textContent.trim().toDoubleOrNull() ?: 0.0
        val note = el.getElementsByTagName("note")
            .item(0).textContent.trim()

        result.add(Expense(amount, category, note))
    }

    return result
}

Ne, yeogiseodo DOM method (getElementsByTagName)ga nam아 있습니다 — geureon데 geugeun jeongsang입니다. XPath-ga modeun geos-eul daechehal piryo-neun eopseumnida. Silmu mokjeok-eun: XPath-ga piryohan “interest point”reul ppa르게 chaj게 (yep: modeun expense) 해주고, 그 다음에는 nested field를 더 익숙한 방식으로 읽는 것입니다.

maineul joghab하고 gyeolgwa 출력

fun main() {
    val doc = parseXml(xml)
    val nodes = selectExpenseNodes(doc)
    val expenses = parseExpenses(nodes)

    for (e in expenses) {
        println("${e.category}: ${e.amount} — ${e.note}")
        // food: 12.5 — Lunch
        // transport: 2.75 — Bus
    }
}

Ije-neun “eodideunji eseo on XML (file, network, integration) i it고, geogiseo entiti moglog-eul 꺼내라” gateun silje taskcheoreom boimnida.

6. Filter wa project-eseo XPath readability

Filter: predicate [...]

Silmueso XPath-ga sarang받는 이유-neun “짧은 경로” 뿐 아니라 filter ttaemun-im니다. Filter-neun 대괄호로, seontaeg-eul 더 구체화합니다. Gajang jaju sseuneun 케이스는 sokseong gijeon filter입니다.

Yegle 들어, kategori가 food인 지출만 piryoh다면, XPath pyohyeon-eun ireoh습니다:

/expenses/expense[@category='food']

이를 kodeuro, choeso화해서 보이겠습니다:

import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathFactory
import org.w3c.dom.NodeList

fun selectFoodExpenses(doc: Any): NodeList {
    val xPath = XPathFactory.newInstance().newXPath()
    val expr = "/expenses/expense[@category='food']"
    return xPath.evaluate(expr, doc, XPathConstants.NODESET) as NodeList
}

Geu daeum “성숙한” 유지보수 생각: filter-neun 짧게 du-neun 게 좋습니다. XPath-ga “maxed-out SQL”처럼 보이기 시작하면, 보통 XPath 안에 비즈니스 로직을 넣으려는 신호입니다. XPath는 seontaeg eoneo 로는 좋지만, “product rule”은 테스트/가독성이 좋은 Kotlin 코드에 두는 편이 낫습니다.

XPath-reul 읽기 쉽게 유지하는 법

Kodbeseu-e XPath-ga 들어오면, 시간이 지나면서 여기저기 늘어납니다. Geureogo discipline eopsi da루면, 이름도 설명도 없는 “jumun munjayeol”만 남습니다. Kode는 돌아가지만… 아무도 touch하길 원치 않게 되죠.

Botong han 가지 간단한 요령이 도움이 됩니다: pyohyeon-eul val로 빼서 의미 있는 이름을 주고, evaluate 안에 바로 박아두지 않습니다.

const val XP_EXPENSES = "/expenses/expense"
const val XP_FOOD_EXPENSES = "/expenses/expense[@category='food']"
const val XP_FIRST_NOTE = "(/expenses/expense/note/text())[1]"

Geu daeum:

val nodes = xPath.evaluate(XP_EXPENSES, doc, XPathConstants.NODESET) as NodeList

Tto han 가지 조심스러운 조언: //는 jeong말 “어디든 찾아라”가 목적일 때만 sse세요. Munseo gujo를 알고 있다면, 명시적인 root path /expenses/expense가 보통 //expenseboda 더 신뢰 가능하고 예측 가능합니다.

7. DOM wieeeseo XPath sayong si heunhan silsu

Silsu No.1: amugeosdo eop-eul ttae XPath-ga nullreul dolyeo jul georago saenggak하기.
Munjayeol modeu eseo evaluate(...)neun dae부분 빈 문자열을 돌려주고, null이 아닙니다. Geu daeum toInt()나 toDouble()을 검증 없이 호출하면, “빈 값”에서 바로 예외가 납니다. 처음부터 xPathTextOrNull(...): String? gateun yutiliti를 만들어 “못 찾음”과 “찾았지만 비었음”을 구분하는 게 편합니다.

Silsu No.2: //reul namyonghae “너무 많은” node-reul 얻기.
//item은 munseo-ga jageul ttae pyeonli해 보입니다. Hajiman XML-i keojigeona, dareun wichi에 nested item이 생기면, 갑자기 불필요한 엔티티까지 import하기 시작할 수 있습니다. Igeon jeong말 gggat-eun bug입니다: kode-ga crash하지 않고, geunyang “틀린 일”을 합니다. Botong root-eseo buteo jeong확한 path로 시작하는 편이 좋습니다.

Silsu No.3: textContent 안의 공백/줄바꿈을 잊기.
Formatting doen XML-eun indent와 줄바꿈을 포함하고, 그것도 텍스트입니다. Geuraeseo textContent나 munjayeol modeu evaluate(...)ga “보이지 않는” 공백이 섞인 값을 돌려주는 일이 흔합니다. trim()을 하지 않으면, “kategori가 분명 food인데 왜 안 맞지?” 같은 이상한 버그를 만날 수 있습니다. Haegsim-eun munjayeol 정규화 discipline입니다.

Silsu No.4: gyeolgwa modeu-reul hon동하고 casting-eseo 터지기.
evaluate(..., NODESET)을 썼다면 NodeList를 기대해야 합니다. 그냥 evaluate(expr, doc)을 썼다면 문자열을 기대해야 합니다. Ige 섞이면, 예기치 않은 순간에 ClassCastException이 발생합니다. selectNodes(...)와 selectText(...)처럼 유틸리티를 둘로 나눠, 이름만 봐도 contract가 보이게 하면 도움이 됩니다.

Silsu No.5: node-가 있는지 확인하지 않고 item(0)부터 잡기.
NodeList는 빈 목록일 수 있습니다. 바로 item(0)을 하고 Element로 캐스팅하면, NullPointerException이나 cast 오류 위험이 있습니다. Import kode에서는 먼저 nodes.length를 확인하는 게 유익합니다. 그리고 “반드시 1개”가 계약이라면, “데이터 없음”을 정직하게 처리하세요 (메시지, null, 예외 등 — 함수 계약에 따라).

Silsu No.6: XPath-reul neomu “똑똑하게” 만들어 biz logic-eul munjayeol 안에 숨기기.
대괄호 안의 표현이 “mini program”처럼 변하면, 유지보수가 급격히 나빠집니다: 디버깅이 어렵고, 읽기 어렵고, 수정하기 어렵습니다. XPath는 잘 드는 칼이지만, 요리 전체를 하는 주방은 아닙니다. Botong XPath로 node를 고르고, 그 다음에 Kotlin에서 필터링/검증하는 편이, 타입과 오류를 통제할 수 있어 더 합리적입니다.

1
과제
Kotlin SELF, 레벨 50, 레슨 2
잠금
XPath로 이름 가져오기
XPath로 이름 가져오기
1
과제
Kotlin SELF, 레벨 50, 레슨 2
잠금
출입증 id
출입증 id
1
과제
Kotlin SELF, 레벨 50, 레슨 2
잠금
쇼핑 목록
쇼핑 목록
1
과제
Kotlin SELF, 레벨 50, 레슨 2
잠금
카테고리 필터
카테고리 필터
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION