我正在使用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句