【问题标题】:Python elementree having hard time extracting dataPython elementtree很难提取数据
【发布时间】:2012-07-12 21:43:26
【问题描述】:

这是 XML:

<top>
    <target>
        <name>TARGET_NAME_1</name>
        <error_count>5</error_count>
        <error_examples>a string goes here</error_examples>
    </target>
    <target>
        <name>TARGET_NAME_2</name>
        <error_count>5</error_count>
        <error_examples>a string goes here</error_examples>
    </target>
</top>

这是我正在尝试的:

tree = ETREE.parse(str(XML_FILE_PATH)) #this seems to work
top = tree.getroot()
targets = top.findall('target')
for target in targets:
    print target

这给了我一个&lt;Element target at HEX_NUMBER&gt;。那么如何提取每个目标的值,即TARGET_NAME_1

干杯

编辑 - 我应该提到我使用的是 Python 2.6 版

【问题讨论】:

    标签: python xml string file


    【解决方案1】:

    假设你想打印所有的名字,你可以这样做:

    import xml.etree.ElementTree as ET
    tree = ET.parse("people.xml")
    top = tree.getroot()
    
    for target in top:
         for x in target:
             if x.tag == 'name': print x.text
    

    获取第一个目标的名称更短:

    print top[0][0].text
    

    但由于它依赖于物品订单,甚至不检查物品是否正确,您可能不应该这样做

    因此要获取所有名称,并且只有名称,我可能会使用如下列表理解:

    [target.find('name').text for target in top]
    

    【讨论】:

    • 是的,这似乎有效。我并不热衷于这样做,但我现在只是想一起破解一些东西。
    【解决方案2】:

    试试target.get('name')

    我是从 http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get 的文档中得到的,看起来它可以满足您的需求。

    【讨论】:

    • 是的,我一直在尝试遵循这一点,但是当我在 for 循环上打印时(使用您的代码行),我得到“无”作为输出。
    • 打印出dir(target)时,有哪些方法可用?尝试target['name']target['error_count'] 会得到什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 2013-09-29
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多