Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Expat 모듈로 빠르게 XML 파싱하기

Python은 내장 모듈인 expat을 통해 XML 데이터를 읽고 처리할 수 있습니다. Expat은 유효성 검사(validation)를 수행하지 않는 경량 XML 파서로, XML 파서 객체를 생성한 뒤 해당 객체의 이벤트를 다양한 핸들러(handler) 함수에 연결하는 방식으로 동작합니다.

핸들러 함수는 문서를 순차적으로 읽으면서 발생하는 이벤트(시작 태그, 종료 태그, 문자 데이터 등)를 실시간으로 가로채 처리합니다. 아래 예제에서는 각 핸들러 함수가 어떻게 XML 파일의 요소와 속성 값을 출력 데이터로 추출하는지 살펴보겠습니다. 이렇게 생성된 데이터는 이후 다양한 형태의 후속 처리에 활용할 수 있습니다.

예제 코드

import xml.parsers.expat
# 첫 번째(시작) 요소 캡처
def first_element(tag, attrs):
    print ('first element:', tag, attrs)
# 마지막(종료) 요소 캡처
def last_element(tag):
    print ('last element:', tag)
# 문자 데이터 캡처
def character_value(value):
    print ('Character value:', repr(value))
parser_expat = xml.parsers.expat.ParserCreate()
parser_expat.StartElementHandler = first_element
parser_expat.EndElementHandler = last_element
parser_expat.CharacterDataHandler = character_value
parser_expat.Parse(""" <?xml version="1.0"?>
<parent student_rollno="15">
<child1 Student_name="Krishna"> Strive for progress, not perfection</child1>
<child2 student_name="vamsi"> There are no shortcuts to any place worth going</child2>
</parent>""", 1)

코드 설명

xml.parsers.expat.ParserCreate()를 호출하면 파서 객체가 생성됩니다. 이후 세 가지 핸들러를 지정합니다.

  • StartElementHandler: 시작 태그를 만날 때 호출되며, 태그 이름과 속성 딕셔너리를 인자로 받습니다.
  • EndElementHandler: 종료 태그를 만날 때 호출되며, 태그 이름만 인자로 전달됩니다.
  • CharacterDataHandler: 태그 사이의 텍스트(문자 데이터)를 만날 때마다 호출됩니다.

Parse() 메서드의 두 번째 인자로 1(True)을 전달하면 입력이 최종 조각임을 의미하며, 파서는 문서 끝까지 한 번에 처리합니다.

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

first element: parent {'student_rollno': '15'}
Character value: '\n'
first element: child1 {'Student_name': 'Krishna'}
Character value: 'Strive for progress, not perfection'
last element: child1
Character value: '\n'
first element: child2 {'student_name': 'vamsi'}
Character value: ' There are no shortcuts to any place worth going'
last element: child2
Character value: '\n'
last element: parent

결과 분석

출력 결과를 보면 파서가 XML 문서를 위에서 아래로 순차적으로 스캔하면서 이벤트를 발생시키는 것을 확인할 수 있습니다. parent 요소의 시작 시점에 속성 student_rollno='15'가 딕셔너리 형태로 전달되며, 각 child 요소에서는 시작 태그 → 문자 데이터 → 종료 태그 순서로 핸들러가 차례대로 호출됩니다. 줄바꿈 문자('\n') 역시 하나의 문자 데이터로 취급된다는 점도 주목할 만합니다.

이처럼 Expat은 대용량 XML 문서를 메모리에 전체 로드하지 않고도 스트림 방식으로 빠르게 처리할 수 있어, 성능이 중요한 XML 파싱 작업에 적합합니다.