使用Python iterparse检索XML属性值

时间:2013-04-08 14:16:59

标签: python xml-parsing elementtree xml-attribute iterparse

我正在尝试使用Python(2.7)中的cElementTree iterparse来了解如何检索XML属性值。我的XML是这样的:

<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()

我正在处理来自stdin的大数据。 我没有运气搞清楚这一点。有人可以告诉你这样做(最佳?)?

1 个答案:

答案 0 :(得分: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':
... 
相关问题