[Python] XML 파싱

최승원·2022년 1월 14일
0

TIL (Today I Learned)

목록 보기
5/21

샘플 데이터는 다음 XML 문서이다.

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

데이터 가져오기

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

XML 데이터는 ElementTree 모듈을 이용하여 root 엘리먼트를 가져오는 방식으로 가져올 수 있다.

자식 노드 액세스

>>> for child in root:
...     print(child.tag, child.attrib)
...
# country {'name': 'Liechtenstein'}
# country {'name': 'Singapore'}
# country {'name': 'Panama'}

for문을 이용하여 현재 엘리먼트의 모든 자식노드에 액세스할 수 있다.

Element 메서드

# Element.iter()

>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
# {'name': 'Austria', 'direction': 'E'}
# {'name': 'Switzerland', 'direction': 'W'}
# {'name': 'Malaysia', 'direction': 'N'}
# {'name': 'Costa Rica', 'direction': 'W'}
# {'name': 'Colombia', 'direction': 'E'}

Element.iter('blabla') 메서드는 특이하게 자식 노드, 자식의 자식 노드 상관 없이 'blabla' 태그를 가진 모든 서브 트리를 이터레이트한다.

# Element.findall(), Element.find(), Element.text, Element.get()

>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
# Liechtenstein 1
# Singapore 4
# Panama 68

Element.findall('blabla') 메서드는 'blabla' 태그를 가진 모든 직접적인 자식 노드를 가져온다.
Elment.find('blabla') 메서드는 'blabla' 태그를 가진 첫번째 자식 노드를 가져온다.
Element.text 메서드는 그 엘리먼트의 텍스트 내용에 액세스한다.
Element.get('blabla') 메서드는 엘리먼트의 'blabla' 어트리뷰트에 액세스한다.

참조

xml.etree.ElementTree — ElementTree XML API

profile
문의 사항은 메일로 부탁드립니다🙇‍♀️

0개의 댓글