【问题标题】:Retrieving XML attribute values using Python iterparse使用 Python iterparse 检索 XML 属性值
【发布时间】:2013-03-30 16:14:03
【问题描述】:

我正在尝试找出如何在 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()

我正在处理来自标准输入的大数据。 我没有运气弄清楚这一点。有人能告诉我如何(最佳?)这样做吗?

【问题讨论】:

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


    【解决方案1】:

    哎呀,盯着我的脸,有点像: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':
    ... 
    

    【讨论】:

    • 检索字典的正确方法是调用:elem.attrib 不需要开括号
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多