Home > Back-end >  Get list of description for each type in xml with Python
Get list of description for each type in xml with Python

Time:10-01

I have a xml file with the following format:

<batch>
 <type1 type="application/pdf" file="1234.pdf">
    <...></...>
    <...></...>
    <description>Description 1</description>
    <...></...>
    <...></...>
 </type1>
 <type2 type="application/pdf" file="23456.pdf">
    <...></...>
    <...></...>
    <description>Description 1</description>
    <...></...>
    <...></...>
 </type2>
 <type1 type="application/pdf" file="1235.pdf">
    <...></...>
    <...></...>
    <description>Description 2</description>
    <...></...>
    <...></...>
 </type1>
</batch>

I want to retrieve a list of type1, type2 within a list of description for that type in the xml. I tried:

test = ET.parse("...\\index.xml")

type_list = []

for type in test.iter():
    type_list.append(type.tag)

type_list = list(set(type_list))

to get all types in xml. But then how can I get all of the description for each type?

The result I want to have:

type1: Description 1, Description 2
type2: Description 1, ...

CodePudding user response:

ugly handling of namespace but should work

import xml.etree.ElementTree as ET
from collections import defaultdict
test = ET.parse("test.xml")

type_list = defaultdict(set)
ns="{blabla.com}"
for type_ in test.iter():
    if type_.tag.startswith(ns 'type'):
        ttag=type_.tag.split(ns)[1]
        descrs = type_.findall(ns 'description')
        for descr in descrs:
            type_list[ttag].add(descr.text)

print(type_list)

CodePudding user response:

see below

import xml.etree.ElementTree as ET
from collections import defaultdict

data = defaultdict(list)
xml = '''<batch>
 <type1 type="application/pdf" file="1234.pdf">
    <description>Description 1</description>
   
 </type1>
 <type2 type="application/pdf" file="23456.pdf">
    <description>Description 1</description>
 </type2>
 <type1 type="application/pdf" file="1235.pdf">
    <description>Description 2</description>
 </type1>
</batch>'''

root = ET.fromstring(xml)

for _type in list(root):
    data[_type.tag].append(_type.find('description').text)
print(data)

output

defaultdict(<class 'list'>, {'type1': ['Description 1', 'Description 2'], 'type2': ['Description 1']})
  • Related