尝试使用 lxml 中的 elementTree 函数通过索引获取元素值无输出
trying to get element value by index with elementTree function in lxml no output
from lxml import etree
from xml.etree import cElementTree as ET
tree = ET.parse(r"D:\General\Python_Preference_validation\sample.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'
from lxml import etree
from xml.etree import cElementTree as ET
tree = ET.parse(r"D:\General\Python_Preference_validation\sample.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'