Files
java-examples/docs/XML DOM Parser.md

7.5 KiB

XML DOM Parser 쉽게 배우기

1. XML DOM Parser란?

DOM(Document Object Model) Parser는 XML 문서를 트리 구조의 객체 모델로 메모리에 로드하여 다루는 방식이다.
XML 데이터를 읽고, 수정하고, 추가하고, 삭제할 수 있다.

장점:

  • 문서를 전체 로드하므로 빠른 검색 및 수정 가능
  • XML을 객체처럼 다룰 수 있음

단점:

  • 메모리 사용량이 큼 (큰 XML을 처리할 때 부담)

2. 주요 메서드 정리

메서드 설명
DocumentBuilderFactory.newInstance() DocumentBuilderFactory 객체 생성
DocumentBuilderFactory.setNamespaceAware(true) 네임스페이스를 인식하도록 설정
DocumentBuilderFactory.setIgnoringElementContentWhitespace(true) 공백 무시
DocumentBuilder.newDocumentBuilder() DocumentBuilder 객체 생성
DocumentBuilder.parse(File file) XML 파일을 Document 객체로 변환
Document.getDocumentElement() XML의 루트 요소 가져오기
Document.getElementsByTagName(String tag) 특정 태그 이름으로 요소 리스트 가져오기
Node.getNodeName() 노드의 이름 반환
Node.getTextContent() 노드의 텍스트 내용 반환
Node.getAttributes() 노드의 속성 반환
Element.getAttribute(String name) 특정 속성 값 가져오기
Element.setAttribute(String name, String value) 속성 추가 또는 변경
Element.appendChild(Node node) 하위 노드 추가
NodeList.getLength() NodeList의 크기 반환
NodeList.item(int index) NodeList에서 특정 인덱스의 노드 반환
TransformerFactory.newInstance() TransformerFactory 객체 생성
TransformerFactory.newTransformer() Transformer 객체 생성
Transformer.transform(Source, Result) XML을 파일 또는 콘솔에 출력

3. XML 문서 예제

아래 XML을 사용하여 실습해보자.

<books>
    <book id="1">
        <title>자바 프로그래밍</title>
        <author>홍길동</author>
        <price>30000</price>
    </book>
    <book id="2">
        <title>데이터베이스 개론</title>
        <author>이몽룡</author>
        <price>25000</price>
    </book>
</books>

4. XML 읽기 (Parsing)

✔ XML을 읽어서 출력하기

아래 코드는 XML을 Document 객체로 로드하고, NodeList를 이용하여 책 정보를 출력한다.

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class XMLParserExample {
    public static void main(String[] args) throws Exception {
        // 1. XML 파일을 로드하여 Document 객체로 변환
        File xmlFile = new File("books.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlFile);

        // 2. 루트 요소 가져오기
        Element root = document.getDocumentElement();
        System.out.println("루트 요소: " + root.getNodeName());

        // 3. 모든 book 요소 가져오기
        NodeList bookList = document.getElementsByTagName("book");

        for (int i = 0; i < bookList.getLength(); i++) {
            Node bookNode = bookList.item(i);

            if (bookNode.getNodeType() == Node.ELEMENT_NODE) {
                Element book = (Element) bookNode;

                // 속성 값 가져오기
                String id = book.getAttribute("id");

                // 하위 요소 가져오기
                String title = book.getElementsByTagName("title").item(0).getTextContent();
                String author = book.getElementsByTagName("author").item(0).getTextContent();
                String price = book.getElementsByTagName("price").item(0).getTextContent();

                System.out.println("책 ID: " + id);
                System.out.println("제목: " + title);
                System.out.println("저자: " + author);
                System.out.println("가격: " + price);
                System.out.println("----");
            }
        }
    }
}

🔹 실행 결과

루트 요소: books
책 ID: 1
제목: 자바 프로그래밍
저자: 홍길동
가격: 30000
----
책 ID: 2
제목: 데이터베이스 개론
저자: 이몽룡
가격: 25000
----

DocumentBuilder.parse(xmlFile)로 XML을 Document 객체로 변환
getElementsByTagName("book")으로 모든 <book> 요소 가져오기
getAttribute("id")속성 값 읽기
getElementsByTagName("title").item(0).getTextContent()텍스트 값 가져오기


5. XML 수정 (노드 추가, 수정, 삭제)

✔ 새로운 <book> 요소 추가하기

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class XMLAddElementExample {
    public static void main(String[] args) throws Exception {
        File xmlFile = new File("books.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlFile);

        Element root = document.getDocumentElement();

        // 새로운 book 요소 생성
        Element newBook = document.createElement("book");
        newBook.setAttribute("id", "3");

        Element title = document.createElement("title");
        title.setTextContent("네트워크 프로그래밍");
        Element author = document.createElement("author");
        author.setTextContent("강감찬");
        Element price = document.createElement("price");
        price.setTextContent("35000");

        // 새 book 요소에 자식 노드 추가
        newBook.appendChild(title);
        newBook.appendChild(author);
        newBook.appendChild(price);

        // 루트 노드에 새로운 book 추가
        root.appendChild(newBook);

        // 변경된 내용을 파일에 저장
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(document), new StreamResult(new File("books.xml")));

        System.out.println("새로운 책 추가 완료!");
    }
}

🔹 실행 후 XML 파일 (books.xml)

<books>
    <book id="1">
        <title>자바 프로그래밍</title>
        <author>홍길동</author>
        <price>30000</price>
    </book>
    <book id="2">
        <title>데이터베이스 개론</title>
        <author>이몽룡</author>
        <price>25000</price>
    </book>
    <book id="3">
        <title>네트워크 프로그래밍</title>
        <author>강감찬</author>
        <price>35000</price>
    </book>
</books>

새로운 <book> 요소를 추가하고 XML 파일을 업데이트


6. 정리

DOM Parser는 XML을 메모리에 로드하여 트리 구조로 다룬다.
DocumentBuilder를 사용해 XML을 Document 객체로 변환
getElementsByTagName()으로 특정 태그의 노드 가져오기
appendChild()로 새로운 노드 추가 가능
Transformer를 사용하여 변경 내용을 XML 파일로 저장

XML을 다룰 때, 읽기/수정/추가가 필요한 경우 DOM Parser가 매우 유용하다!