Import the read_xml_file
and the read_xml_string
classes and use accordingly
from xml_stream import read_xml_file, read_xml_string
xml_string = """
<company>
<staff>
<operations_department>
<employees>
<team>Marketing</team>
<location name="head office" address="Kampala, Uganda" />
<bio first_name="John" last_name="Doe">John Doe</bio>
<bio first_name="Jane" last_name="Doe">Jane Doe</bio>
<bio first_name="Peter" last_name="Doe">Peter Doe</bio>
</employees>
<employees>
<team>Customer Service</team>
<location name="Kampala branch" address="Kampala, Uganda" />
<bio first_name="Mary" last_name="Doe">Mary Doe</bio>
<bio first_name="Harry" last_name="Doe">Harry Doe</bio>
<bio first_name="Paul" last_name="Doe">Paul Doe</bio>
</employees>
</operations_department>
</staff>
</company>
"""
file_path = '...'
for element in read_xml_string(xml_string, records_tag='staff'):
print(element)
for element_as_dict in read_xml_string(xml_string, records_tag='staff', to_dict=True):
print(element_as_dict)
"""
{
'operations_department': {
'employees': [
[
{
'team': 'Marketing',
'location': {
'name': 'head office',
'address': 'Kampala, Uganda'
},
'first_name': 'John',
'last_name': 'Doe',
'_value': 'John Doe'
},
{
'team': 'Marketing',
'location': {
'name': 'head office',
'address': 'Kampala, Uganda'
},
'first_name': 'Jane',
'last_name': 'Doe',
'_value': 'Jane Doe'
},
{
'team': 'Marketing',
'location': {
'name': 'head office',
'address': 'Kampala, Uganda'
},
'first_name': 'Peter',
'last_name': 'Doe',
'_value': 'Peter Doe'
}, ],
[
{
'team': 'Customer Service',
'location': {
'name': 'Kampala branch',
'address': 'Kampala, Uganda'
},
'first_name': 'Mary',
'last_name': 'Doe',
'_value': 'Mary Doe'
},
{
'team': 'Customer Service',
'location': {
'name': 'Kampala branch',
'address': 'Kampala, Uganda'
},
'first_name': 'Harry',
'last_name': 'Doe',
'_value': 'Harry Doe'
},
{
'team': 'Customer Service',
'location': {
'name': 'Kampala branch',
'address': 'Kampala, Uganda'
},
'first_name': 'Paul',
'last_name': 'Doe',
'_value': 'Paul Doe'
}
],
]
}
}
"""
for element in read_xml_file(file_path, records_tag='staff'):
print(element)
for element_as_dict in read_xml_file(file_path, records_tag='staff', to_dict=True):
print(element_as_dict)