【发布时间】:2014-05-19 12:53:31
【问题描述】:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for i in tree.findall('.//rank'):
print ET.tostring(i)
这里我想获取所有排名元素(保持其绝对结构)
我得到的输出为
<rank>1</rank>
<rank>4</rank>
<rank>68</rank>
我应该怎么做才能得到输出为
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
</country>
<country name="Singapore">
<rank>4</rank>
</country>
<country name="Panama">
<rank>68</rank>
</country>
</data>
当输入xml文件country_data.xml为
<?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>
【问题讨论】:
标签: python xml xpath elementtree