2013-04-08 139 views
2

我想了解如何使用Python(2.7)中的cElementTree iterparse檢索XML屬性值。我的XML是這樣的:使用Python檢索XML屬性值iterparse

<root> 
    <record attr1="a" attr2="b" attr3="c" ... /> 
    <record attr1="x" attr2="y" attr3="z" ... /> 
    ... 
</root> 

我的代碼是這樣的:

context = ET.iterparse(sys.stdin, events=('start','end')) 
context = iter(context) 
event, root = context.next() 

for event, elem in context: 
    if event == 'end' and elem.tag == 'record': 
     # get the attributes!! 
    elem.clear() 
    root.clear() 

我處理標準輸入大數據。 我沒有任何運氣可以搞清楚這一點。有人可以告訴我(最佳?)如何做到這一點?

回答

3

哎呀,盯着我的臉,那種:http://docs.python.org/2/library/xml.etree.elementtree.html#element-objects

總結:

elem.get('attr_name', default_value) 

,或者

for name, value in elem.items(): 

,或者

elem.attrib() - dictionary 

我應該還補充說這是必要的薩利修改張貼在問題的代碼:通過調用

... 
if event == 'start' and elem.tag == 'record': 
... 
+0

檢索字典正確的方法是: elem.attrib不需要 開括號 – ealbert 2014-12-04 12:36:55