0

I know there are several xml parsers for python, but I dont know which one would be good to parse outputs of mysql xml, I havent been successfully yet. The output looks like:

<resultset statement="select * from table where id > 5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <row>
    <field name="name">first</field>
    <field name="login">2021-08-16 13:44:35</field>
  </row>

  <row>
    <field name="name">second</field>
    <field name="login">2021-08-18 13:44:35</field>
  </row>
</resultset>

because the structure is quite simple here, I come about to write my own parser, but I would guess there should be already something to cover this case?!

Output should be a list of dicts with columns as keys and the value as the content of the row/column

3
  • Take a look at ElementTree: docs.python.org/3/library/xml.etree.elementtree.html Commented Aug 24, 2021 at 9:14
  • what is the expected output? Commented Aug 24, 2021 at 9:19
  • @balderman a list with dicts like [{name:first,login:2021-08-16},{...}] Commented Aug 24, 2021 at 14:35

1 Answer 1

1

see below

import xml.etree.ElementTree as ET

xml = '''<resultset statement="select * from table where id > 5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <row>
    <field name="name">first</field>
    <field name="login">2021-08-16 13:44:35</field>
  </row>

  <row>
    <field name="name">second</field>
    <field name="login">2021-08-18 13:44:35</field>
  </row>
</resultset>'''

data = []
root = ET.fromstring(xml)
for row in root.findall('.//row'):
    fields = []
    for field in row.findall('field'):
        fields.append((field.attrib['name'], field.text))
    data.append(fields)
print(data)

output

[[('name', 'first'), ('login', '2021-08-16 13:44:35')], [('name', 'second'), ('login', '2021-08-18 13:44:35')]]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I changed the loop with record = dict() for field in row.findall('field'): record[field.attrib['name']] = field.text data.append(record) to get a better output strucutre

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.