[英]How to reading out row from xml with elementTree using Python?
我是使用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>
通过此代码,我尝试使用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)
但是唯一的打印输出是None
。
你知道我在做什么吗?
我也想用account="1930"
打印出每一行。 在这种情况下,我想要这样打印:
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'])
您做错的是,您正在尝试通过查看元素的文本来访问元素属性。
如ElementTree官方文档中所述, Element.text
包含在element标记之间找到的任何文本 ,这意味着在<row>this is the text in "text"</row>
。
如果要访问名为row
的元素的属性account
,则需要调用Element.attrib
, 该字典包含该元素的属性 :
for i in xmltree.getiterator('row'):
account = i.attrib['account']
if account == '1930':
print('account')
注意:从版本2.7(或3.2) getiterator
,不建议使用getiterator
:请改用方法ElementTree.iter()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.