sankar
sankar

Reputation: 357

Parsing elements to dict

I am new to python programming and i am working on getting the ind_elements from the xml file to a dict.

I was able to parse the file and get the output. the output of the file trough the code are as follows:

The code is as follows:

for ind_list in reflist:
    for i in ind_list.attributes.keys():
        print(ind_list.attributes[i].name)
        print(ind_list.attributes[i].value)  




name
sankar
title
student
age
25
user_2
2012-05-08
user_3
2012-05-08

name
sankar
title
student
age
25
user_1
2012-05-08
user_2
2012-05-08

name
sankar
title
student
age
25
user_4
2012-05-08
user_5
2012-05-08

The issue right now are as follows: 1) I want to insert these elements into a dictionary. I want to insert it dynamically. 2) As you can see from the output, each and every line of the xml file is different. How to add a key dynamically into the dict and not to add it, when it is already present?

I want these individual values to insert it into the database. I have worked with database coding from a dict before. So i can code that part.

Upvotes: 0

Views: 195

Answers (2)

Sascha Gottfried
Sascha Gottfried

Reputation: 3329

Do not waste time creating dicts. Just iterate over xml and create database queries.

This style of processing is more natural for some operations, such as converting XML input to some other format. This technique can be used to convert list of podcasts from the earlier examples from an XML file to a CSV file, so they can be loaded into a spreadsheet or database application.

Look at this approach and tell us why this is not working for you.

Upvotes: 0

myildirim
myildirim

Reputation: 2428

You should use xmltodict then, from xmltodict document;

>>> doc = xmltodict.parse("""
... <mydocument has="an attribute">
...   <and>
...     <many>elements</many>
...     <many>more elements</many>
...   </and>
...   <plus a="complex">
...     element as well
...   </plus>
... </mydocument>
... """)
>>>
>>> doc['mydocument']['@has']
u'an attribute'
>>> doc['mydocument']['and']['many']
[u'elements', u'more elements']
>>> doc['mydocument']['plus']['@a']
u'complex'
>>> doc['mydocument']['plus']['#text']
u'element as well'

Upvotes: 1

Related Questions