2012-07-12 28 views
2

这里是XML:Python的elementree有很难提取数据

<top> 
    <target> 
     <name>TARGET_NAME_1</name> 
     <error_count>5</error_count> 
     <error_examples>a string goes here</error_examples> 
    </target> 
    <target> 
     <name>TARGET_NAME_2</name> 
     <error_count>5</error_count> 
     <error_examples>a string goes here</error_examples> 
    </target> 
</top> 

这里是我尝试:

tree = ETREE.parse(str(XML_FILE_PATH)) #this seems to work 
top = tree.getroot() 
targets = top.findall('target') 
for target in targets: 
    print target 

这给了我<Element target at HEX_NUMBER>。那么如何提取每个目标的价值,即TARGET_NAME_1

干杯

编辑 - 我要指出,我在Python版本2.6

回答

2

说你想打印所有的名字,你可以做象下面这样:

import xml.etree.ElementTree as ET 
tree = ET.parse("people.xml") 
top = tree.getroot() 

for target in top: 
    for x in target: 
     if x.tag == 'name': print x.text 

较短获得第一目标的名字:

print top[0][0].text 

但因为它依赖于项目订单,甚至不检查项目是否正确,你可能不应该这样做

因此,要获得所有的名称和唯一的名字,我可能会使用如下的列表理解:

[target.find('name').text for target in top] 
+0

是的,这似乎工作。我对这样做并不是疯狂的,但我现在只是想要一起破解一些东西。 – JDS 2012-07-12 22:11:48

2

尝试target.get('name')

我从http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get的文档中得到了这个消息,看起来它就是你要找的东西。

+0

是的,我一直在试图遵循这一点,但当我通过for循环打印(使用您的代码行)时,输出“None”作为输出。 – JDS 2012-07-12 21:49:33

+0

打印出目标(dir)时,有哪些方法可用?当你尝试'target ['name']'或target ['error_count']'时,你会得到什么? – girasquid 2012-07-12 21:52:09