簡體   English   中英

如何使用Python使用elementTree從xml讀取行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM