我有以下XML页面结构:
<address>
<city>Anaheim</city>
<state>California</state>
<zip>92801</zip>
<country>United States</country>
</address>
<address>
<city>Berkley</city>
<state>California</state>
<zip>94705</zip>
<country>United States</country>
</address>
我想只获取城市标签的值,其中zip标签值符合条件。 例如,我需要那些城市名称,其中zip = 92801。
python中有一种简单的方法可以做到这一点吗?
答案 0 :(得分:2)
这将达到预期的效果:
my_string = '''
<root>
<address>
<city>Anaheim</city>
<state>California</state>
<zip>92801</zip>
<country>United States</country>
</address>
<address>
<city>Berkley</city>
<state>California</state>
<zip>94705</zip>
<country>United States</country>
</address>
</root>
'''
from lxml import etree
root = etree.fromstring(my_string)
cities = root.xpath('.//zip[text()="92801"]/preceding-sibling::city')
答案 1 :(得分:1)
你如何使用ElementTree
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
filtered_addresses = []
for address in root.findall('address'):
if address.get('zip') == '92801':
filtered_addresses.append(address)
答案 2 :(得分:0)
如果你想改用美丽的汤:
my_string = '''
<root>
<address>
<city>Anaheim</city>
<state>California</state>
<zip>92801</zip>
<country>United States</country>
</address>
<address>
<city>Berkley</city>
<state>California</state>
<zip>94705</zip>
<country>United States</country>
</address>
</root>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(my_string, 'html.parser')
desired_zips = soup.findAll('zip', text="92801")
cities = []
for zip_tag in desired_zips:
cities.append(zip_tag.findPreviousSibling('city'))
print(cities)
<强>输出:强>
[<city>Anaheim</city>]
注意:您可以将此for
循环写入列表推导,但它看起来很笨重且不可读。