gpt4 book ai didi

python - 使用 pythton xml 获取特定子值的属性

转载 作者:行者123 更新时间:2023-12-01 08:57:27 25 4
gpt4 key购买 nike

如何获取“实验室符号”的“组名称”457的“来源”值

<?xml version="1.0" encoding="UTF-8"?>
<tabgroup1 name1="CRDT" revision="19531">
<client name="123" group="457" />

<group name="457">
<lab symbol="xyz/ght" sources="SBS,TCS,DDT" />
<lab symbol="pqr/xyz" sources="RRT,QQR,XXC" />

</group>

<group name="345">
<lab symbol="xyz/ght" sources="GHB,GRT,BNM" />

</group>


</tabgroup1>

我使用以下步骤进行了测试:Python: access nested children in xml file parsed with ElementTree但输出会打印所有属性。

最佳答案

您可以使用BeautifulSoup :

data = '''<?xml version="1.0" encoding="UTF-8"?>
<tabgroup1 name1="CRDT" revision="19531">
<client name="123" group="457" />
<group name="457">
<lab symbol="xyz/ght" sources="SBS,TCS,DDT" />
<lab symbol="pqr/xyz" sources="RRT,QQR,XXC" />
</group>
<group name="345">
<lab symbol="xyz/ght" sources="GHB,GRT,BNM" />
</group>
</tabgroup1>'''

soup = BeautifulSoup(data, 'lxml')

result = [j['sources'] for i in soup.find_all('group', {'name': '457'}) for j in i.find_all('lab')]
result
#['SBS,TCS,DDT', 'RRT,QQR,XXC']

使用 xml 也可以实现同样的效果:

import xml.etree.ElementTree as ET

data = '''<?xml version="1.0" encoding="UTF-8"?>
<tabgroup1 name1="CRDT" revision="19531">
<client name="123" group="457" />
<group name="457">
<lab symbol="xyz/ght" sources="SBS,TCS,DDT" />
<lab symbol="pqr/xyz" sources="RRT,QQR,XXC" />
</group>
<group name="345">
<lab symbol="xyz/ght" sources="GHB,GRT,BNM" />
</group>
</tabgroup1>'''

tree = ET.fromstring(data)
result = [j.attrib['sources'] for i in tree.findall('group') if i.attrib['name'] == '457' for j in i.findall('lab')]
result
#['SBS,TCS,DDT', 'RRT,QQR,XXC']

关于python - 使用 pythton xml 获取特定子值的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52698840/

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