使用Python iterparse获取XML属性值

4

我正在尝试使用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个回答

4

正确检索字典的方法是调用: elem.attrib不需要使用开括号。 - ealbert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接