Im new using Python, now I have a problem using ElementTree
and read out values from an xml with this structure:
<entry number="47" date="2011-01-29">
<name>Swedbank-taxe</name>
<row account="1930" debit="0" credit="16712"/>
<row account="8415" debit="1781" credit="0"/>
<row account="2734" debit="14931" credit="0"/>
</entry>
<entry number="48" date="2011-01-29">
<name>Agri - Calcium</name>
<row account="1930" debit="0" credit="2000"/>
<row account="1471" debit="400" credit="0"/>
<row account="4370" debit="1600" credit="0"/>
</entry>
With this code I try to print out the content of every row with the label="row"
:
from tkinter import filedialog
from xml.etree.ElementTree import ElementTree as ET
xmltree = ET()
filval=filedialog.askopenfilename()
xmltree.parse(filval)
konton = xmltree.getiterator('row')
for i in konton:
print (i.text)
But the only print out is None
.
Do you know what I'm doing wrong?
Also I would like to print out every row with account="1930"
. In this case I would like a print out like this:
1930
1930
from tkinter import filedialog
from xml.etree.ElementTree import ElementTree as ET
xmltree = ET()
filval=filedialog.askopenfilename()
xmltree.parse(filval)
konton = xmltree.getiterator('row')
for i in konton:
# remove this to print the account from every row
if i.attrib['account'] == "1930":
print (i.attrib['account'])
What you're doing wrong is that you're trying to access an element attribute by looking at its text.
As explained in the official ElementTree documentation Element.text
contain any text found between the element tags , which means that in <row>this is the text in "text"</row>
.
If you want to access the attribute account
of your element named row
, you need to call Element.attrib
, a dictionary containing the element's attributes :
for i in xmltree.getiterator('row'):
account = i.attrib['account']
if account == '1930':
print('account')
Note: The use of getiterator
is deprecated since version 2.7 (or 3.2): Use method ElementTree.iter()
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.