Thursday, November 10, 2011


Python: lxml insert element before and after given element



from lxml import etree
xml = etree.parse('old_xml.xml')
count = 1
for pp in xml.xpath('/response/items/item'):
   prod_id = etree.Element('new_element')  # this element will be inserted
   prod_id.text = "%s" % count
   nav = pp.find('name')  # we will insert before/after this element
   div = nav.getparent()
   pp.insert(pp.index(nav), prod_id) # insert before 'name'
   pp.insert(pp.index(nav) + 1, prod_id) # insert after 'name'
   count += 1

out = open('new_xml.xml','w')
out.write(etree.tostring(xml, pretty_print=True))
out.close()

No comments: