CodeGym /행동 /Kotlin SELF /DOM parsing: Document, Element, attributes, and textConte...

DOM parsing: Document, Element, attributes, and textContent

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

1. Seoron

Man약 han beonirado substringBefore("</tag>") 로 “XML-eul parsing” hanneun 코드르 봤다면, du gaji sasil-eul algo itseul geoyeyo: geureon 코드는 gakkeumeun jeongmallo doedogie… geurigo geuraeseo deo wiheomhamnida. DOM parsing-eun XML-eul memory aneseo 객체 트리로 bakkuneun gil입니다. Uri-neun munjayeo “모서리(엣지)” reul jabneun geot-eul meomchugo, file explorer-eseo 폴더를 tteodaenineun geotcheoreom 구조(reul) 따라 “geonneun” geot-eul sijakhapnida.

DOM-eun 문서가 neomu keuji anhgo, uri-ga data-ui yeoreoun bu-bun-eul 자유롭게 꺼내야 할 때 pyeonrihapnida. 네, DOM-eun XML 전체를 memory-e 올립니다 (pyeon-ui-ui daega). Hajiman geu da-eumeseo uri-neun root element-reul 꺼내고, attribute-reul bogo, 모든 <expense> reul chatgo, <amount> an-ui 텍스트를 읽는 등 다양하게 다룰 su it습니다.

Geurigo gippeun bounseu: JVM-ui Kotlin-eun Java API-reul seumun eopsi buleul su itgo, DOM parser-neun gajang jeontongjeogin Java 도구입니다. 즉, uri-neun split() 과 “바람(희망)” eulo jajeongeo reul jaejag-haji 않고, 시간 검증된 라이브러리를 geudaero sayonghal geoyeyo. Kotlin-eun Java-wa 상호운용 (interop) doeneun 언어로 jeongche eul 잡go itseunikka, “Kotlin-eseo Java DOM API-reul 호출” 하는 geon jeongmal ilbanjeogin 실무 시나리오입니다.

DOM parsing mini pipeline

Jasehan geos-euro deuleogagi jeone, jeonche peuroseoseu-ui jido(reul) han beon mandeureo bopsida. DOM 접근에서는 보통 du dan-gye-ga 있습니다: meonjeo XML-eul Document 로 파싱하고, geu da-eum 그 트리에서 data-reul 추출합니다.

A-rae-neun gan-danhan flowchart입니다 (네, 프로그래머는 화살표(reul) geuryeoseo 디버깅 할 때 deol 울려고 합니다):

flowchart TD
    A[XML as String / file] --> B["DocumentBuilder.parse(...)"]
    B --> C[Document]
    C --> D[documentElement: Element]
    D --> E[Find elements / read attributes / textContent]
    E --> F[Your Kotlin objects / strings / numbers]

I beon lecture-eseo-neun E 블록까지(포함) gae nyaeng: 올바르게 Document reul 얻는 beop, an jeonhage Element reul 꺼내는 beop, attribute-wa text-reul 읽는 beop.

2. DOM model: Document, Element, NodeList

코드를 쓰기 jeone, 용어 정리가 도움이 됩니다. DOM-eun “Document Object Model”, 문서를 트리로 보는 모델입니다. 트리의 꼭대기는 문서 자체, geu 아래는 요소(태그), 요소 안에는 다른 요소들과 텍스트가 있습니다.

Moei-ga 한 번에 da 외우려 하지 않도록, 간단히 이렇게 생각하면 됩니다: XML → tree → nodes.

A-rae-ui jageun 대응표는 “XML 개념” 과 “DOM 클래스” 를 헷갈리지 않게 도와줍니다:

In XML In DOM (JVM) What it means in code
The whole document
org.w3c.dom.Document
A “box” that contains the whole tree
Tag <user>...</user>
org.w3c.dom.Element
An element node: tag name, attributes, and content
Attribute id="42"
Element.getAttribute("id")
Get the attribute’s string value
A set of similar tags <item>...</item>
org.w3c.dom.NodeList
A DOM collection: length + index access
Text inside a tag
Element.textContent
All text inside the element (often with spaces/newlines)

Chobo-ja-ga jal bbeonhaneun jung-yo han “hamjeong”: NodeList 는 List ga 아닙니다. map, forEach, indices 같은 Kotlin collection-ui pyeon-ui 기능이 없습니다. DOM 세상에서는 종종 “옛날 방식” eulo 살게 됩니다: 0 until nodes.length 그리고 nodes.item(i).

3. XML-eseo Document 얻기

XML string → Document

Document reul 얻으려면 DOM parser-ga 필요합니다. Java/JVM-eseo-neun factory인 DocumentBuilderFactory reul 통해 DocumentBuilder reul 만들고, DocumentBuilder ga parse(...) reul 할 수 있습니다.

Gajang minimal han 예시로 sijakhapnida: XML-i Kotlin string 안에 바로 있습니다.


import javax.xml.parsers.DocumentBuilderFactory

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

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

    println(doc.documentElement.tagName) // user
}

byteInputStream() reul jom jomyeon hae bopsida. Parser-neun bo-tong byte stream (InputStream) 으로 일하고, string-eun uri-ege pyeonliham입니다. Uri-neun string-eul byte stream-euro bakkwoseo parser-ege neomgimnida.

Yeogi-eun silljeong jeok saenggak han 가지: XML-eun text지만 parser-neun bytes reul 읽습니다. Silmusaeseo-neun encoding-e daehae jinjja mani saenggak하게 되겠지만, i lecture beomwi-eseo-neun han 가지 gyuchikman al면 충분합니다: “parser-neun ‘그냥 string’ i 아니라 InputStream reul badneunda.”

Root element: documentElement

Document reul 얻었다면, “안에 뭐가 있지?” ga 궁금해집니다. Sijak jeom은 geoui hangsang han 가지: root element입니다.

doc.documentElement 는 Element reul 반환합니다. I geosi 트리의 root (모든 것을 감싸는 “맨 위 태그”) 입니다.

import javax.xml.parsers.DocumentBuilderFactory

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

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

    val root = doc.documentElement
    println(root.tagName) // user
}

Wae jungyohal까요? Da-eum bu-teo-neun “컨텍스트 기반” eulo 읽는 일이 많기 때문입니다: meonjeo root-ga <expenses> ga 맞는지 확인한 뒤, geu 안에서 <expense> reul 찾습니다. Ireohge 하면 코드가 더 예측 가능해지고 (그리고 스스로에게 deomyeo-neun magie-reul jogeum julil su 있습니다).

XML from file: parse(File)

XML-i string i 아니라 file 로 들어오는 경우(klasik한 “report export”), 바로 읽고 싶어집니다. DOM parser-neun 중간에 readText() 없이도 file 을 파싱할 수 있어서, file 을 meonjeo string 으로 읽을 필요가 없습니다.

Mini 예시 “file → Document”:

import java.io.File
import javax.xml.parsers.DocumentBuilderFactory

fun parseXmlFile(path: String) =
    DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(File(path))

Usage:

import org.w3c.dom.Element

fun main() {
    val doc = parseXmlFile("expenses.xml")
    val root = doc.documentElement

    println(root.tagName) // expenses
    val first = root.getElementsByTagName("expense").item(0) as? Element
    println(first?.getAttribute("id")) // e.g.: e1
}

Wae pyeonlihal su it나요? parse(File) ga 알아서 stream-eul 열고 data-reul 읽기 때문입니다. 반대로 File(path).readText() 후 parse(...) 를 하면, meonjeo keun string-eul memory-e 만들고, geu da-eum tto bytes 로 bakkum니다. Jageun file-eun gwaenchanh지만, “큰 data-reul 불필요하게 boksa하지 않는다” reul seumgwanhwa-haneun geon 대체로 좋은 습관입니다.

Parsing errors and try/catch

DOM parser-neun 꽤 엄격합니다: XML-i well-formed ga 아니면 예외를 던집니다. I geon jeongsang입니다: tag 닫는 것을 빼먹었을 때 parser-ga 당신 의도를 맞출 의무는 없습니다. (물론, 차를 가져다주고 공감하며 끄덕여주면 jinjja johe겠지만요.)

Parsing-eul try/catch 로 감싸는 것은 좋은 실무 습관입니다. 특히 CLI 앱에서는 “그냥 죽지 말고 계속” 하고 싶을 때가 많습니다.

import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val brokenXml = "<user><name>Ann</user>" // name tag is not closed

    try {
        DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(brokenXml.byteInputStream())

        println("Parsed OK")
    } catch (e: Exception) {
        println("XML parse failed: ${e.message}")
    }
}

Yeogiseo-neun Exception 을 매우 넓게 잡습니다 (학습 예제로는 충분합니다). 실무 코드에서는 더 구체적인 타입을 잡는 일이 많지만, 지금은 아이디어가 더 중요합니다: “parsing-eun 예외가 날 수 있는(= 잠재적으로 실패하는) 작업이다.”

4. DOM-eseo data 읽기: attributes, elements, text

Attributes: getAttribute(...)

XML attribute는 id="42" 처럼 생겼습니다. DOM-eseo-neun 이렇게 읽습니다:

import javax.xml.parsers.DocumentBuilderFactory

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

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

    val id = doc.documentElement.getAttribute("id")
    println(id) // 42
}

그런데 yeogiseo “jaemi있는” 포인트가 시작됩니다: 많은 사람은 attribute가 없으면 null 이 올 거라고 기대합니다. 하지만 getAttribute(...) 는 보통 empty string 을 반환합니다.

import javax.xml.parsers.DocumentBuilderFactory

fun main() {
    val xml = """<user></user>"""

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

    val id = doc.documentElement.getAttribute("id")
    println("id='$id'") // id=''
}

즉, “attribute가 있는데 비어 있음” 과 “attribute가 없음” 이 동일하게 보입니다 — 둘 다 "" 를 돌려줍니다. 그래서 실무에서는 거의 항상 추가 검사(reul) 합니다:

val id = root.getAttribute("id").trim()
val idOrNull = id.takeIf { it.isNotEmpty() }

trim() 을 쓰는 이유는, attribute 값이 공백을 포함할 수도 있기 때문입니다 (그리고 " " 같은 값을 의미 있는 값으로 받아들이고 싶지 않겠죠).

Finding elements: getElementsByTagName(...)

Root를 얻었다면, 다음 전형적인 step은 nested element를 찾는 것입니다. 가장 간단한 방법은 getElementsByTagName("name"). 이 메서드는 NodeList 를 반환합니다.

Mini 예시:

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

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

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

    val nodes = doc.getElementsByTagName("name")
    println(nodes.length) // 1

    val nameEl = nodes.item(0) as Element
    println(nameEl.tagName) // name
}

Yeogiseo nuansu-ga yeoreo ga-ji 있습니다:

Cheotjjae, nodes.length 는 element 개수입니다. 만약 length == 0 이면, item(0) 이 null 을 반환하고, as Element 캐스팅이 프로그램을 터뜨립니다. 그래서 규칙은 간단합니다: 먼저 검사, 그다음 접근.

Duljjae, getElementsByTagName 는 직계 자식만이 아니라 subtree 전체 에서 찾습니다. 즉, 예를 들어 <user><profile><name>...</name></profile></user> 라면, user.getElementsByTagName("name") 는 <profile> 안에 있는 <name> 도 찾습니다. Ttaeron pyeonli하고, ttaeron yegiji mothan 동작입니다. 지금 단계에서는 “검색이 깊다” 는 것만 기억하면 됩니다.

빈 결과에서 터지지 않으려면 안전 캐스팅인 as? 와 null 체크를 쓸 수 있습니다:

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

fun main() {
    val xml = """<user></user>"""

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

    val nameEl = doc.getElementsByTagName("name").item(0) as? Element
    println(nameEl?.tagName) // null
}

Text inside a tag: textContent

Ije gajang “masitneun” bu-bun-euro: <name>Ann</name> 안의 값을 어떻게 꺼내나요?

DOM-eseo-neun textContent 로 합니다:

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

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

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

    val nameEl = doc.getElementsByTagName("name").item(0) as Element
    println(nameEl.textContent) // Ann
}

Geureonde sallalhan hyeonsil 예시: XML은 종종 사람 친화적으로 들여쓰기와 줄바꿈으로 예쁘게 포맷합니다. 사람에게는 좋지만, parser에게는 그것도 텍스트입니다.

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

fun main() {
    val xml = """
        <user>
            <name>
                Ann
            </name>
        </user>
    """.trimIndent()

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

    val nameEl = doc.getElementsByTagName("name").item(0) as Element
    println(nameEl.textContent)          // "\n                Ann\n            "
    println(nameEl.textContent.trim())   // Ann
}

Geuraeseo trim() 을 textContent 옆에 두는 것은 “just in case” 가 아니라 사실상 표준 위생(standard hygiene)에 가깝습니다.

Tto han 가지: textContent 는 element 내부의 모든 텍스트 를 반환합니다. 포함: nested element 안의 텍스트. 예:

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

fun main() {
    val xml = """<msg>Hello <b>World</b>!</msg>"""

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

    val msgEl = doc.documentElement
    println(msgEl.textContent.trim()) // Hello World!
}

I geon jeongsang입니다. 다만 이해해야 합니다: textContent 는 “안에 있는 텍스트 전부” 지, “직접 자식 텍스트 노드만” 이 아닙니다.

Jageun DOM hygiene: 코드를 더 ‘안정적으로’ 만들기

DOM 코드를 쓰기 시작하면, 전형적인 유혹이 생깁니다: 어디서나 item(0) as Element 를 하고 “세상은 착하다”고 믿는 것. 세상은 착하지 않습니다. 단지 아직 당신에게 <amount> 를 빠뜨리거나, <Amount> 처럼 다른 대소문자(= case-sensitive universe)로 쓴 XML을 보여주지 않았을 뿐입니다.

그래서 좋은 스타일은, 검증/ trim() / 안전 캐스팅을 숨기는 작은 helper 함수를 뽑아두는 것입니다. 다음 섹션에서 바로 그렇게 할 겁니다 — firstTagText 가 등장하고, 메인 parsing 코드는 더 읽기 쉬워지고, 체크 로직은 한 곳에 모이게 됩니다.

Tto 유용한 테크닉: 읽는 즉시 문자열을 정규화(normalize)하기. trim(), ttaeron lowercase() (형식이 허용한다면), 빈 값 체크 등. DOM parsing은 거의 항상 “data preprocessing” 과 짝입니다. 안 그러면 category = " food " 같은 값을 얻고, 나중에 왜 grouping이 안 되는지 놀라게 됩니다.

5. Example: XML-eseo expenses를 import해서 list로 만들기

예시들이 “진공 속” 에서 따로 놀지 않도록, 익숙한 로직에 DOM 읽기를 끼워 넣어 봅시다: 지출 관리 콘솔 앱이 있고, 어느 날 회계팀(또는 은행)이 export를 주는데… XML입니다. 왜냐하면 “historically it happened that way”. 묻지 마세요. “사무실 프린터가 왜 다정하게 부탁해야만 동작하는가” 같은 것입니다.

XML이 이렇게 생겼다고 합시다:

<expenses>
  <expense id="e1">
    <amount>120.50</amount>
    <category>food</category>
    <comment>Lunch</comment>
  </expense>
</expenses>

간단하게 expense model을 하나 두겠습니다 (프로젝트에 이미 있다면 그걸 쓰세요. 여기서 중요한 건 모델이 아니라 DOM 추출입니다):

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

Ije jageun helper를 만듭니다: parent 안에서 첫 번째 tag 의 텍스트를 꺼내기. 포인트: element가 없을 수 있으니 String? 을 반환합니다.

import org.w3c.dom.Element

fun firstTagText(parent: Element, tag: String): String? {
    val node = parent.getElementsByTagName(tag).item(0) as? Element ?: return null
    return node.textContent.trim()
}

그다음 메인 함수: XML을 파싱해서 Expense 리스트를 얻기.

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

fun parseExpenses(xml: String): List<Expense> {
    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    val nodes = doc.getElementsByTagName("expense")
    val result = mutableListOf<Expense>()

    for (i in 0 until nodes.length) {
        val expenseEl = nodes.item(i) as? Element ?: continue

        val id = expenseEl.getAttribute("id").trim()
        val amount = firstTagText(expenseEl, "amount")?.toDoubleOrNull()
        val category = firstTagText(expenseEl, "category")
        val comment = firstTagText(expenseEl, "comment") ?: ""

        if (id.isNotEmpty() && amount != null && category != null) {
            result.add(Expense(id, amount, category, comment))
        }
    }

    return result
}

Yeogiseo-neun 의도적으로 “현실적인” 기법을 썼습니다: toDoubleOrNull(), null 체크, trim(). 아직 예쁜 error system을 만들지는 않습니다 — 지금은 “DOM을 읽되, 입력이 조금만 달라도 안 터지게” 하는 감각이 더 중요합니다. 입력 데이터는 거의 항상 “가끔은 정상, 가끔은… 뭐, 아시죠” 이니까요.

Mini input으로 테스트:

fun main() {
    val xml = """
        <expenses>
            <expense id="e1">
                <amount>120.50</amount>
                <category>food</category>
                <comment>Lunch</comment>
            </expense>
            <expense id="e2">
                <amount>999</amount>
                <category>tech</category>
                <comment>Keyboard</comment>
            </expense>
        </expenses>
    """.trimIndent()

    val items = parseExpenses(xml)
    println(items.size)        // 2
    println(items.first().id)  // e1
}

6. DOM parsing-eseo jaeju naneun 실수들

Mistake №1: length 검사 없이 item(0) 잡기.
가장 흔한 갑작스러운 crash 원인입니다. XML에서는 element가 없을 수 있습니다: 옛 버전 포맷 파일, 다른 공급자, 단순 실수 등. 만약 nodes.item(0) 을 as Element 로 캐스팅하면, 빈 NodeList 에서는 item(0) 이 null 을 반환하고, 그다음 캐스팅에서 터지거나, 조금 뒤에 NPE가 날 수 있습니다. 해결: “먼저 검사, 그다음 접근” 습관 또는 as? 와 빠른 return.

Mistake №2: getAttribute(...) 가 null을 준다고 기대하기.
초보는 종종 val id = el.getAttribute("id") ?: ... 같은 코드를 쓰고, 왜 ?: 가 동작하지 않는지 놀랍니다. getAttribute 는 보통 빈 문자열을 반환하므로, 이건 완전히 다른 로직 분기입니다. 결과적으로 trim() 과 isNotEmpty() 없이면, attribute 부재를 “값이 있네?” 로 받아들일 수 있습니다.

Mistake №3: textContent 에서 trim() 을 잊고 “보이지 않는” 공백을 얻기.
XML 포맷팅(들여쓰기, 줄바꿈)도 텍스트입니다. 그래서 textContent 는 "\n 120.50\n" 같은 값을 가질 수 있고, "120.50" 이 아닐 수 있습니다. 그 상태에서 toDouble() 을 하거나 문자열 비교를 하면, “예쁜데 왜 안 되지?” 같은 오류가 생깁니다. 학습 예제에서는 사소해 보이지만, 실무에서는 “왜 숫자가 parsing 안 되지, 분명 숫자인데” 로 몇 시간 디버깅이 되기도 합니다.

Mistake №4: getElementsByTagName 이 직계 자식만 찾는다고 생각하기.
이 메서드는 subtree 전체에서 찾습니다. 그래서 가끔 예기치 않은 결과가 나옵니다: 특정 <expense> 안의 <amount> 만 찾고 싶었는데, nested block 안이나 다른 곳의 <amount> 까지 전부 섞여 나오기도 합니다 (구조가 복잡할수록 더). 작은 문서에서는 티가 안 나다가, 어느 날 “첫 번째 <amount>” 가 엉뚱한 값이 됩니다. 이 단계에서는 규율이 살립니다: 필요한 element(컨텍스트)에서부터 찾기, 그리고 XML 구조를 최대한 명확하게 유지하기.

1
과제
Kotlin SELF, 레벨 50, 레슨 1
잠금
사용자 프로필
사용자 프로필
1
과제
Kotlin SELF, 레벨 50, 레슨 1
잠금
누락된 id
누락된 id
1
과제
Kotlin SELF, 레벨 50, 레슨 1
잠금
책 제목
책 제목
1
과제
Kotlin SELF, 레벨 50, 레슨 1
잠금
상품 진열
상품 진열
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION