为什么这个例子只返回最后一个子属性,我怎么能得到它们呢?
输入:
<root c1="A" c2="B"</root>
<root c1="A" c2="C"</root>
脚本:
data = ElementTree.parse("./test.xml").getroot()
def getLetters(data):
for child in data:
if child.attrib['c1']:
c1 = child.attrib['c1']
if child.attrib['c2']:
c2 = child.attrib['c2']
return c1, c2
print getLetters(data)
结果总是被覆盖,我得到了最后一个孩子。
我已尝试过收益但仍有同样的问题:
yield c1, c2
generator = getLetters(data)
for i in generator:
print i
答案 0 :(得分:1)
您在函数中所做的是迭代您在xml中碰巧拥有的所有元素对。完成迭代后,返回最终赋值的c1和c2的值(甚至可能不是来自同一个子,代码的编写方式),这些值将是最后一对元素或者c1和c2对应的到那个xml中的最后一次出现(因为你没有对先前获得的值对做任何事情)。
这里有两种方法:
1)创建一个结构,例如一个元组列表,或者更好的是字典,并继续在那里添加你的(c1,c2)元素:
def getLetters(data):
result = []
for child in data:
# use other default values here if more suitable
c1 = None
c2 = None
if child.attrib['c1']:
c1 = child.attrib['c1']
if child.attrib['c2']:
c2 = child.attrib['c2']
result.append({'c1':c1, 'c2':c2}) # append your next entry as a mini-dictionary
return result
for entry in getLetters(data):
print 'c1', entry['c1'], 'c2', entry['c2']
2)使用yield可能是处理大块数据的更有效方法,因为在进一步传递之前不必等到它全部处理完毕。
def getLetters(data):
for child in data:
# use other default values here if more suitable
c1 = None
c2 = None
if child.attrib['c1']:
c1 = child.attrib['c1']
if child.attrib['c2']:
c2 = child.attrib['c2']
yield {'c1':c1, 'c2':c2} # yield the mini-dictionary for every child
# no return needed here
# you can process the output in the same way:
for entry in getLetters(data):
print 'c1', entry['c1'], 'c2', entry['c2']
答案 1 :(得分:0)
class getLetters:
def __init__(self):
self.c1 = child.attrib['c1']
self.c2 = child.attrib['c2']
for child in data:
i = getLetters()
c1 = i.c1
c2 = i.c2
print c1, c2