from lxml import etree
from xml.etree import cElementTree as ET
tree = ET.parse(r"D:GeneralPython_Preference_validationsample.xml")
root = tree.getroot()
root[0][1].text
这是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"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
我希望将输出作为2008,但是当我运行脚本时,它不会提供任何输出或抱怨任何语法错误。粘贴了一个代码和XML
您可能只有print
print root[0][1].text # output '2008'