5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonでXMLの読み込みと書き込み

Posted at

Pytho で XML を読み書きするサンプルコードです。
以前は xml.dom を使っていましたが ElementTree を使うと楽にできました。
役に立てば幸いです。

Pythonコード

main.py
# -*- coding: UTF-8 -*-
from xml.dom import minidom
import xml.etree.ElementTree as ET

def save_xml():
  root = ET.Element('root')
  elem1 = ET.SubElement(root, 'elem1')
  elem2 = ET.SubElement(elem1, 'elem2')
  
  # 子ノードを追加
  elem3_1 = ET.SubElement(elem2, 'elem3')
  elem3_1.set('attr1','1234')
  elem3_1.set('attr2','abcd')
  elem3_1.text = 'value1' 

  # 子ノードを追加
  elem3_2 = ET.SubElement(elem2, 'elem3')
  elem3_2.set('attr1','5678')
  elem3_2.set('attr2','efgh')
  elem3_2.text = 'value2' 

    # インデントを付けて保存
  doc = minidom.parseString(ET.tostring(root, 'utf-8'))
  with open('test.xml','w') as f:
    doc.writexml(f, encoding='utf-8', newl='\n', indent='', addindent='  ')

def read_xml():
  tree = ET.parse('test.xml')
  root = tree.getroot()

  # findall()は直下のみなのでiter()を使用
  elems = root.iter('elem3') 
  for e in elems:
    print('attr1='+e.get('attr1')+' attr2='+e.get('attr2')+ ' test=' + e.text)

save_xml()
read_xml()    

save_xml() の結果

test.xml
<?xml version="1.0" encoding="utf-8"?>
<root>
  <elem1>
    <elem2>
      <elem3 attr1="1234" attr2="abcd">value1</elem3>
      <elem3 attr1="5678" attr2="efgh">value2</elem3>
    </elem2>
  </elem1>
</root>

read_xml() の結果

attr1=1234 attr2=abcd test=value1
attr1=5678 attr2=efgh test=value2
5
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?