简体   繁体   中英

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

Here is the XML file:

<?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>

I am expecting to get output as 2008 but when I run the script it does not providing any output nor complaining about any syntax error. pasted a code and xml as well

可能您只需要print

print root[0][1].text # output '2008'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM