如何使用变量lxml-xpath传递属性值



如何将属性作为变量传递,当我对值进行硬编码时,我会得到结果,但当我分配变量时却不会

<rootdata>
<Config id="1A" cId="1A13" name="Confg 13">
<Assignment _id="id1eF"  of_end_="id1588"/>
<Assignment _id="id1F0"  of_end_="id1598" />
</Config>
<Config id="2A" cId="2A14" name="Confg 14">
<Assignment _id="id1eF"  of_end_="id151"/>
<Assignment _id="id1F0"  of_end_="id152" />
</Config>

<Config id="3A" cId="3A15" name="Confg 14">
<Assignment _id="id1eF"  of_end_="id153"/>
<Assignment _id="id1F0"  of_end_="id154" />
</Config>
<ele id="id1ef" name="name1"/>
<ele id="id1f0 name="name2"/>
</rootdata>
tree = ET.parse('data.xml')
root = tree.getroot()

for config in root.findall("./Config/[@cId='1A13']/Assignment"):    
temp_id=config.attrib['_id']
temp_of_end=config.attrib['of_end_']
print(temp_id,tmp_of_end)

当我硬编码cId的值时,它有效,但我想传递一个变量我的var

for config in root.findall("./Config/[@cId=myvariable]/Assignment"): 

尝试按如下方式传递变量:

myvariable = "1A13"
root.findall("./Config/*[@cId='{}']/Assignment".format(myvariable))

最新更新