Python XML 파서 파서는 XML 파일에서 유용한 정보를 읽고 추출하는 가장 쉬운 방법 중 하나를 제공합니다. 이 짧은 튜토리얼에서는 python ElementTree XML API를 사용하여 XML 파일을 구문 분석하고 XML 문서를 수정 및 생성하는 방법을 볼 것입니다.
Python ElementTree API는 XML 데이터를 추출, 구문 분석 및 변환하는 가장 쉬운 방법 중 하나입니다.
이제 ElementTree를 사용하여 Python XML 파서를 사용하여 시작해 보겠습니다.
예시 1
XML 파일 생성
먼저 요소와 하위 요소가 있는 새 XML 파일을 만들 것입니다.
#Import required library
import xml.etree.ElementTree as xml
def createXML(filename):
# Start with the root element
root = xml.Element("users")
children1 = xml.Element("user")
root.append(children1)
tree = xml.ElementTree(root)
with open(filename, "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
createXML("testXML.xml") 위의 프로그램을 실행하면 현재 기본 작업 디렉토리에 "textXML.xml"이라는 새 파일이 생성됩니다.

다음과 같은 내용이 포함되어 있습니다.
<users><user /></users>
파일을 작성하는 동안 'wb' 모드를 사용했습니다. 바이너리 모드로 파일을 작성하십시오.
XML 요소에 값 추가
위 프로그램에서 XML 요소에 몇 가지 값을 지정해 보겠습니다.
#Import required library
import xml.etree.ElementTree as xml
def createXML(filename):
# Start with the root element
root = xml.Element("users")
children1 = xml.Element("user")
root.append(children1)
userId1 = xml.SubElement(children1, "Id")
userId1.text = "hello"
userName1 = xml.SubElement(children1, "Name")
userName1.text = "Rajesh"
tree = xml.ElementTree(root)
with open(filename, "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
createXML("testXML.xml") 위의 프로그램을 실행하면 다음과 같은 값으로 새 요소가 추가되는 것을 볼 수 있습니다.
<users> <user> <Id>hello</Id> <Name>Rajesh</Name> </user> </users>
위의 출력은 괜찮아 보입니다.
이제 파일 편집을 시작하겠습니다.
XML 데이터 편집
기존 프로그램의 파일에 데이터를 추가해 보겠습니다.
newdata.xml
<users> <user> <id>1a</id> <name>Rajesh</name> <salary>NA</salary> </user> <user> <id>2b</id> <name>TutorialsPoint</name> <salary>NA</salary> </user> <user> <id>3c</id> <name>Others</name> <salary>NA</salary> </user> </users>
위는 현재 xml 파일입니다. 각 사용자의 급여를 업데이트해 보겠습니다.
#Import required library
import xml.etree.ElementTree as ET
def updateET(filename):
# Start with the root element
tree = ET.ElementTree(file=filename)
root = tree.getroot()
for salary in root.iter('salary'):
salary.text = '500000'
tree = ET.ElementTree(root)
with open("newdata.xml", "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
updateET("newdata.xml") 출력

따라서 급여가 'NA'에서 '500000'으로 변경된 것을 볼 수 있습니다.
예:Python XML 파서
이제 파일에 있는 XML 데이터를 구문 분석하고 데이터를 인쇄하는 다른 프로그램을 작성해 보겠습니다.
#Import required library
import xml.etree.cElementTree as ET
def parseXML(file_name):
# Parse XML with ElementTree
tree = ET.ElementTree(file=file_name)
print(tree.getroot())
root = tree.getroot()
print("tag=%s, attrib=%s" % (root.tag, root.attrib))
# get the information via the children!
print("-" * 25)
print("Iterating using getchildren()")
print("-" * 25)
users = root.getchildren()
for user in users:
user_children = user.getchildren()
for user_child in user_children:
print("%s=%s" % (user_child.tag, user_child.text))
if __name__ == "__main__":
parseXML("newdata.xml") 출력
<Element 'users' at 0x0551A5A0>
tag = users, attrib = {}
-------------------------
Iterating using getchildren()
-------------------------
id = 1a
name = Rajesh
salary = 500000
id = 2b
name = TutorialsPoint
salary = 500000
id = 3c
name = Others
salary = 500000