我正在尝试了解如何在cElementTree (2.7)中使用cElementTree检索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的大数据。我没有任何运气来弄清楚这件事。谁能告诉我是怎么做到的(最优的?)来做这个吗?
发布于 2013-04-08 22:35:03
哦,盯着我的脸,有点像: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':
... https://stackoverflow.com/questions/15881497
复制相似问题