[英]How to reading out row from xml with elementTree using Python?
Im new using Python, now I have a problem using ElementTree
and read out values from an xml with this structure: 我是使用Python的新手,现在我在使用ElementTree
遇到问题,并从具有以下结构的xml中读取值:
<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"
: 通过此代码,我尝试使用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
. 但是唯一的打印输出是None
。
Do you know what I'm doing wrong? 你知道我在做什么吗?
Also I would like to print out every row with account="1930"
. 我也想用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>
. 如ElementTree官方文档中所述, Element.text
包含在element标记之间找到的任何文本 ,这意味着在<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 : 如果要访问名为row
的元素的属性account
,则需要调用Element.attrib
, 该字典包含该元素的属性 :
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. 注意:从版本2.7(或3.2) getiterator
,不建议使用getiterator
:请改用方法ElementTree.iter()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.