All about Programming

python으로 xml element value 변경

민토즈 2021. 1. 19. 20:53
300x250

xml elelment value를 변경하는 방법에 대한 설명입니다.

<filename> element에 확장자명이 빠진 201만 입력된 상태이며, python으로 filename element를 찾고,

확장자 .png를 붙여서 저장하는 방법의 코드를 작성합니다. 

 

 

<annotation verified="no">
  <filename>201</filename>
  <source>
    <database>Unknown</database>
  </source>
  <size>
    <width>881</width>
    <height>716</height>
    <depth>3</depth>
  </size>
  <segmented>0</segmented>
 </annotation>
import xml.etree.ElementTree as ET

xml_file = "sample.xml"
tree = ET.parse(xml_file)
root = tree.getroot()
root.find('filename').text = root.find('filename').text + '.png'

tree.write(xml_file, encoding='UTF-8', xml_declaration=True)

root.find('filename').txt를 호출하면 201이 return되고 확장자 .png를 붙여서

root.find('filename').txt에 <filename> element 위치에 201.png를 저장합니다. 

300x250