简体   繁体   中英

value not getting updated in ElementTree in lxml

I'm using lxml in python.

from lxml import etree
d = etree.parse("input.xml")
t1 = etree.Element('year')
t2 = etree.Element('gdppc')
t1.text = '2016'
t2.text = '123456'

When I print t1 and t2,

print etree.tostring(t1)
print etree.tostring(t2)

Correct output is printed. But it's not getting updated in 'd'.

print etree.tostring(d)

input.xml:

<?xml version="1.0"?>
<data>
   <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>        
</data>

How to update it in 'd'?

d is not related to t1 or t2 in any way. By doing etree.Element('year') or etree.Element('gdppc') you are initializing new independent elements . Instead, if you want to update existing year or gdppc elements inside d , find them first:

d = etree.parse("input.xml")

t1 = d.find('.//year')
t2 = d.find('.//gdppc')

t1.text = '2016'
t2.text = '123456'

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