gpt4 book ai didi

python - 如何在Python中从xml文档中获取特定标签

转载 作者:行者123 更新时间:2023-12-01 05:13:20 24 4
gpt4 key购买 nike

我正在使用 etree 和 lxml,

我可以使用 xpath 获取节点的文本,但我想要包括标签的整个内容

<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/> First Country
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/> Second Country
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/> Third Country
</country>
</data>

如果我给出国家/地区,我希望文本返回为

<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/> First Country
</country>

现在使用的代码是

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for i in tree.findall('.//country'):
print i.text

最佳答案

这对你有用吗?

for i in tree.findall('.//country'):
print ET.tostring(i)

关于python - 如何在Python中从xml文档中获取特定标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23737482/

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