파이썬에서 XML 파일이나 문자열을 파싱하고, Tag나 attribute 별로 Element를 읽는 방법을 소개합니다.
1. XML 파일 파싱
ElementTree.parse(file)
는 인자로 전달된 파일을 파싱하고 ElementTree 객체로 리턴합니다.
import xml.etree.ElementTree as ET
filePath = "./example.xml"
tree = ET.parse(filePath)
ET.dump(tree)
Output:
<Countries><Korea><City>Seoul</City></Korea><Japanese><City>Tokyo</City></Japanese></Countries>
1.1 파싱한 객체를 보기 좋게 출력 : Text에 Tab, 개행 문자 추가
위의 코드에서, _pretty_print()
를 추가로 구현하여, 파싱한 xml 객체의 text에 Tab과 개행 문자를 추가하면 다음과 같이 보기 좋게 출력할 수 있습니다.
import xml.etree.ElementTree as ET
def _pretty_print(current, parent=None, index=-1, depth=0):
for i, node in enumerate(current):
_pretty_print(node, current, i, depth + 1)
if parent is not None:
if index == 0:
parent.text = '\n' + ('\t' * depth)
else:
parent[index - 1].tail = '\n' + ('\t' * depth)
if index == len(parent) - 1:
current.tail = '\n' + ('\t' * (depth - 1))
filePath = "./example.xml"
tree = ET.parse(filePath)
_pretty_print(tree.getroot())
ET.dump(tree)
Output:
<Countries>
<Korea>
<City attr1="value1" attr2="value2">Seoul</City>
</Korea>
<Japanese>
<City attr1="value1" attr2="value2">Tokyo</City>
</Japanese>
</Countries>
2. XML 문자열 파싱
ElementTree.fromstring()
은 XML 문자열을 인자로 받고, 파싱한 결과를 Element 객체로 리턴합니다.
import xml.etree.ElementTree as ET
xml_str = "<Countries><Korea><City>Seoul</City></Korea><Japanese><City>Tokyo</City></Japanese></Countries>"
element = ET.fromstring(xml_str)
ET.dump(element)
Output:
<Countries><Korea><City>Seoul</City></Korea><Japanese><City>Tokyo</City></Japanese></Countries>
3. XML 파싱하고, 요소 별로 읽기
다음과 같이 XML을 파싱하여 Element 객체를 얻고 요소 별로 접근할 수 있습니다. findall()
로 모든 태그를 찾을 수 있고, attrib
로 Element의 attribute에 접근할 수 있습니다. XML의 텍스트는 text
로 접근할 수 있습니다. Element의 하위 Element는 find()
나 findall()
로 접근할 수 있습니다.
import xml.etree.ElementTree as ET
xml_str = '''<?xml version='1.0' encoding='utf-8'?>
<Countries>
<Country name="Korea">
<City attr1="value1" attr2="value2">Seoul</City>
</Country>
<Country name="Japanese">
<City attr1="value1" attr2="value2">Tokyo</City>
</Country>
</Countries>
'''
root = ET.fromstring(xml_str)
for country in root.findall("Country"):
attr = country.attrib
name = attr.get("name")
city = country.find("City")
city_name = city.text
city_attr1 = city.attrib.get("attr1")
city_attr2 = city.attrib.get("attr2")
print(f"attr : {attr}")
print(f"name : {name}")
print(f"attr : {attr}")
print(f"city_name : {city_name}")
print(f"city_attr1 : {city_attr1}")
print(f"city_attr2 : {city_attr2}")
Output:
attr : {'name': 'Korea'}
name : Korea
attr : {'name': 'Korea'}
city_name : Seoul
city_attr1 : value1
city_attr2 : value2
attr : {'name': 'Japanese'}
name : Japanese
attr : {'name': 'Japanese'}
city_name : Tokyo
city_attr1 : value1
city_attr2 : value2
Loading script...
Related Posts
- Python 소수점 반올림, round() 예제
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- 파이썬 주석 처리, 단축키 소개
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - 딕셔너리 정리 및 예제
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 반복문으로 리스트 순회 방법 (+ Index 출력)
- Python - with로 파일 열고 닫기