나중에 내가 보려고 만든 블로그

[Python] ElementTree 사용하여 xml 파싱, 수정하기 본문

Python

[Python] ElementTree 사용하여 xml 파싱, 수정하기

winches 2022. 3. 10. 11:01

https://docs.python.org/ko/3/library/xml.etree.elementtree.html

 

xml.etree.ElementTree — ElementTree XML API — Python 3.10.2 문서

소스 코드: Lib/xml/etree/ElementTree.py xml.etree.ElementTree 모듈은 XML 데이터를 구문 분석하고 만들기 위한 단순하고 효율적인 API를 구현합니다. 버전 3.3에서 변경: 이 모듈은 가능할 때마다 빠른 구현을

docs.python.org

 

해당 문서 참고하여 기본적인 기능 사용해보았다.

xml 파일을 수정하고 난 뒤 write 할때 xml 파일이 indent 없이 한줄로 쭉 이어서 수정되어있다면

본문 제일 아래 코드블럭에 있는 indent 함수를 사용하면 된다.  

 

원본 xml은 이런 형태인데 if문 사용하여 특정 조건에 부합하면 xml이 수정되도록 해보았음.

아래는neighbor 엘리먼트에서 attribute direction이 "E"인 경우 "Non"으로 수정한 결과임.

위와 같은 xml이 여러개 있는 경우 아래처럼 하나의 경로에 넣고 반복문으로 수정할 수 있다,

아래는 indentation, write까지해서 다시 수정한 xml을 저장한 코드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import os
import xml.etree.ElementTree as ET 
from xml.etree.ElementTree import Element, SubElement, ElementTree, dump
import pandas as pd
 
file_path = "/data/"
file_list = os.listdir(file_path)
pd.set_option('display.max_rows'None)
 
## indentation
def indent(elem, level=0): 
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i
 
for fl_nm in file_list :           
    tree = ET.parse( file_path + fl_nm )
    root = tree.getroot()  
    n_roof = 1 
        
    for neighbor in root.iter("neighbor") :
        if(neighbor.attrib["direction"== "E") :
            neighbor.attrib["direction"= "Non"
                
    indent(root)
    tree = ElementTree(root)
    tree.write( file_path + fl_nm  )
    print(  "#" + fl_nm + "done")
cs

반복적인 일을 최대한 효율적으로 하고자 xml 파싱을 시작한거라서 자주 사용했다.