7
3

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 5 years have passed since last update.

xmltodictは配下の要素が1つの場合list化しない

Posted at

xmltodictは配下の要素が1つの場合list化しない

TL;DR

  • xmltodict は配下の要素が1つの場合list化しない (2つ以上の場合list化される)
  • 要素が1つの場合もlist化したい場合は、 parse時にforce_listオプションを利用する

要素が2つの場合 -> foods配下が list化されている

import xmltodict

xml = """
<foods>
  <food>
    <name>バナナ</name>
    <color>黄色</color>
  </food>
  <food>
    <name>リンゴ</name>
    <color>赤</color>
  </food>
</foods>
"""

parsed_xml = xmltodict.parse(xml)
print(type(parsed_xml["foods"]["food"]))

# <class 'list'>

要素が1つの場合 -> foods配下が list化されていない


import xmltodict

xml = """
<foods>
  <food>
    <name>バナナ</name>
    <color>黄色</color>
  </food>
</foods>
"""

parsed_xml = xmltodict.parse(xml)
print(type(parsed_xml["foods"]["food"]))
  
# <class 'collections.OrderedDict'>

どうするか

parse するときに force_list オプションを指定する(対象にする要素名はタプルで指定可能)


import xmltodict

xml = """
<foods>
  <food>
    <name>バナナ</name>
    <color>黄色</color>
  </food>
</foods>
"""

parsed_xml = xmltodict.parse(xml, force_list=('food'))
print(type(parsed_xml["foods"]["food"]))
  
# <class 'list'>
7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?