如何从python中的xml文档中获取特定标记

时间:2014-05-19 12:13:54

标签: python xpath lxml elementtree

我正在使用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 个答案:

答案 0 :(得分:2)

这对你有用吗?

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