LoginSignup
5
8

More than 3 years have passed since last update.

xml.etree.ElementTreeの使い方

Posted at

Python 3.8.2

xml.etree.ElementTree --- ElementTree XML API

パース

ファイルから

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

文字列から

root = ET.fromstring(country_data_as_string)

検索

タグで現在の要素の 直接の子要素 のみ検索

# Listが返ってくる
list = root.findall('country'):

タグで最初に見つかった要素だけ検索

elem = root.find('country'):

XPath式で検索

root.findall("./country/neighbor")

コンテンツと属性へのアクセス

コンテンツにアクセス

rank = country.find('rank').text

属性にアクセス

 # どちらでも
 country.get('name')
 country.attrib['name']

子要素の生成

elem = ET.SubElement(root,'country')
elem = ET.SubElement(root,'country', attrib={'name':'Liechtenstein'})

子要素の削除

>>> for country in root.findall('country'):
...     # using root.findall() to avoid removal during traversal
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...

出力

sys.stdoutに出力

ET.dump(root)

ファイルに出力

  • 改行されないので見にくい
tree = ET.ElementTree(root)
tree.write('filename', encoding="utf-8", xml_declaration=True)

改行付きでファイルに出力

import xml.dom.minidom as md
document = md.parseString(ET.tostring(root, 'utf-8'))
with open(fname,'w') as f:
    document.writexml(f, encoding='utf-8', newl='\n', indent='', addindent='  ')

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8