如何在Python中从XML文档中获取特定标签

1 投票
1 回答
1361 浏览
提问于 2025-04-18 06:59

我正在使用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

1 个回答

2

这样做对你有用吗?

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

撰写回答