在中使用xpath时如何获取父标记xml.etree.elementree使用python 2.6.4

2024-06-01 22:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是这个论坛的新手。在

我试图从中检索数据xml.etree.cElementTree. 在

我有以下代码

代码片段

import xml.etree.cElementTree as ET

xmldata ="""
<pipeline>
    <ep_150>
        <stage name="lay" longname="layout" department="layout" process="production">
            <review name="R1" reviewer="sridhar reddy" role="supervisor" id="p1234">
            </review>
        </stage>
        <stage name="lip" longname="lipsync" department="lipsync" process="production">
            <review name="R2" reviewer="someone" role="supervisor" id="p2345">
            </review>
        </stage>
        <stage name="blk" longname="blocking" department="animation" process="production">
            <review name="R3" reviewer="sudeepth" role="supervisor" id="p4645" dependson='R1'>
            </review>
            <review name="R4" reviewer="chandu" role="director" id="p5678">
            </review>
        </stage>
        <stage name="pri" longname="primary" department="animation" process="production">
            <review name="R5" reviewer="sudeepth" role="supervisor" id="p4645" style="dep" >
            </review>
            <review name="R6" reviewer="sudeepth" role="bld_supervisor" id="p2556" style="dep">
            </review>
        </stage>
        <stage name="sec" longname="secondary" department="animation" process="production">
            <review name="R7" reviewer="sha" role="supervisor" id="p1234" style="dep">
            </review>
            <review name="R8" reviewer="chandu" role="director" id="p5678">
            </review>
        </stage>
    </ep_150>
</pipeline>
"""
root = ET.fromstring(xmldata)

stages = root.findall("./ep_150/stage")

print 'Stages in animation department....\n'

for stage in stages:

    if stage.attrib['department']=='animation':
        print stage.attrib['name']

review = root.findall("./ep_150/stage/review")        

print '\n\nreviews for id=p4645\n'

for rev in review:

    if rev.attrib['id']=='p4645':
        print (rev.attrib['name'])

通过上面的代码,我得到的结果如下

动画系的舞台。。。。在

黑色

pri公司

id=p4645的评论

第3页

R5型

但我需要下半年的输出为

id=p4645的被检阅人

黑色-R3

pri-R5型

也就是说,我需要元素的父标记


Tags: nameidprocessstagereviewroleproductionep
1条回答
网友
1楼 · 发布于 2024-06-01 22:31:27

孩子们不知道他们的父母,但是父母知道他们的孩子们,所以你必须相应地构建你的代码:

stages = root.findall("./ep_150/stage")        

print '\n\nreviews for id=p4645\n'

for stage in stages:
    for rev in stage.findall('review'):
        if rev.attrib['id']=='p4645':
            print stage.attrib['name'], rev.attrib['name']

http://effbot.org/zone/element.htm#accessing-parents

与答案无关。如果你愿意,你可以在findall参数中移动那些if:

^{pr2}$

相关问题 更多 >