아래와 같은 xml 파일이 있다면,
위 xml글에서 가장 조상이 되는 root요소는 <data>이고,
그 하위 요소(tag)로 <country>, <country>의 하위요소(tag)로
<rank>, <year>, <gdppc>,<neighbor>이 있다.
이 요소를 파이썬에서 조회하는 방법을 정리하자면,
<?xml version="1.0" encoding="utf-8"?>
<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>
|
1. 모듈 불러오기
root를 선언
import xml.etree.ElementTree as ET
tree = ET.parse(r'파일위치\파일이름.xml')
root = tree.getroot()
2. 모든 요소(tag)조회
모든 요소를 조회할 때는 'root.iter()'를 사용한다.
#예제
for i in root.iter():
print(i.tag)
#결과값
data
country
rank
year
gdppc
neighbor
neighbor
country
rank
year
gdppc
neighbor
country
rank
year
gdppc
neighbor
neighbor
3. 모든 요소(tag)의 개수 구하기
모든 요소의 개수를 구할때 'len()'함수로는 구해지지 않는다.
##실패예제 - len()함수로 구하기
print(len(root.iter()))
따라서 아래와 같은 방법으로 구할수 있다.
#예제 - 모든 요소(tag)의 개수 구하기
root_iter = []
for i in root.iter():
root_iter.append(i.tag)
print(len(root_iter))
#결과값
18
5. root 요소(tag)
root요소는 1개 이므로 개수를 구하는 것은 생락하고 root요소(tag)이름을 조회하는 방법은 아래와 같다.
#예제 - root요소 조회
print(root.tag)
#결과값
data
4. root요소(tag)의 하위 요소(tag)와 갯수조회
root의 바로 하위 요소, <country>를 조회하는 방법은 아래와 같이
'root'를 조회하여
#예제 - root요소(tag)의 하위 요소(tag)조회
for child in root:
print(child.tag)
#결과값
country
country
country
개수를 조회하는 방법은 아래와 같다.
#예제 - root요소(tag)의 하위 요소(tag)개수조회
print(len(root))
#결과값
3
4. 하위요소(tag)의 바로 아래 하위 요소(tag)와 갯수조회
<country>요소의 바로 아래 하위요소를 구하는 방법은 3번의 for 문에 다른 for 문을 붙여서 구할수 있다.
#예제 - 하위요소(tag)의 하위 요소(tag) 조회
for child in root.iter('country'):
print('-',child.tag)
for child_2 in child:
print(child_2.tag)
#결과값
- country
rank
year
gdppc
neighbor
neighbor
- country
rank
year
gdppc
neighbor
- country
rank
year
gdppc
neighbor
neighbor
개수를 구하는 방법은 두가지가 있다.
1) 'root.findall()' 함수를 사용하여 구하기
#root요소(tag)의 하위 요소(tag) 개수조회1
for child in root.findall('country'):
print(child.tag)
print(len(child))
#결과값
country
5
country
4
country
5
2) range(0, <country>요소 개수)만큼 'len()'함수를 사용하여 구하기
#root요소(tag)의 하위 요소(tag) 개수조회2
for i in range(0,len(root)):
print(len(root[i]))
#결과값
5
4
5
위의 과정을 거치면서 알게된 것은
아래와 같이 태그를 조화하는 값, ex) root, root[0]을 사용하면 해당 태그가 나오며
len함수를 사용해서 바로 하위 태그 개수를 구할수 있다.
print(root.tag)
print(len(root))
print(root[0].tag)
print(len(root[0]))
#값
data
3
country
5
'프로그래밍 > PYTHON' 카테고리의 다른 글
파이썬 명령어/ 기초구문 (0) | 2023.11.21 |
---|---|
파이썬 함수(def)에서 괄호의 의미 (0) | 2023.11.15 |
파이썬 클래스 - 사용 시 주의 사항 (0) | 2023.11.15 |
파이썬 4cam 으로 동영상 재생하는 코드 (0) | 2023.11.09 |
(Python) 파이썬으로 텍스트 읽기 (0) | 2023.01.04 |