gpt4 book ai didi

python - 使用子节点 lxml python 获取父节点

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:13 24 4
gpt4 key购买 nike

对于这个xml

 xmldata="""
<locations>

<continent region="Africa" >
<country id="84" countryname="Algeria" ></country>
</continent>

<continent region="Asia" >
<country id="84" countryname="India" ></country>
</continent>

<continent region="America" >
<country id="84" countryname="Mexico" ></country>
</continent>

</locations>
"""

我正在尝试使用国家/地区名称获取地区名称,如果国家/地区名称是印度,则代码应返回亚洲

我已经尝试过了,

import lxml.etree as ET
root = ET.fromstring(xmldata)
flag=False
continent=""
country=""
for neighbor in root.iter('continent'):
for i in neighbor.iter("country"):
if i.attrib.get('countryname')=="India":
flag=True
continent=neighbor.attrib.get('region')
country=i.attrib.get('countryname')
if flag==True:
break
print 'Continent is ',continent , 'And country is ', country

这段代码可以工作,但是这不是一个方便的方法。

如何使用 xpath 表达式实现此目的?

最佳答案

使用//大陆[./country/@countryname="India"]/@region xpath表达式:

>>> import lxml.etree as ET
>>> xmldata="""
... <locations>
...
... <continent region="Africa" >
... <country id="84" countryname="Algeria" ></country>
... </continent>
...
... <continent region="Asia" >
... <country id="84" countryname="India" ></country>
... </continent>
...
... <continent region="America" >
... <country id="84" countryname="Mexico" ></country>
... </continent>
...
... </locations>
... """
>>> root = ET.fromstring(xmldata)
>>> print root.xpath('//continent[./country/@countryname="India"]/@region')
['Asia']

关于python - 使用子节点 lxml python 获取父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23341082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com