0
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?

Pythonのxml.etree.ElementTreeモジュールを使ってXMLを整形

Last updated at Posted at 2024-12-23
xmlsample.py
import xml.etree.ElementTree as ET

def indent(elem, level=0):
    """ElementTreeのXMLツリーをインデントして整形する関数"""
    i = "\n" + "  " * level
    if len(elem):  # 子要素がある場合
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        for child in elem:
            indent(child, 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

# サンプルのXMLデータ
data = """
<root>  <child>    <subchild>data</subchild>  </child>  <child>    <subchild>data2</subchild>  </child></root>
"""

# XMLデータをパース
tree = ET.ElementTree(ET.fromstring(data))
root = tree.getroot()

# インデントを追加
indent(root)

# 整形されたXMLを出力
print(ET.tostring(root, encoding="unicode"))
python xmlsample.py

<root>
  <child>
    <subchild>data</subchild>
    </child>
  <child>
    <subchild>data2</subchild>
    </child>
  </root>

0
0
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
0
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?