
Hi,
Von: Jens Tröger <jens.troeger@light-speed.de> I've been scratching my head over the following question, and can't quite figure this out. Any comments are appreciated :)
http://stackoverflow.com/questions/23282241/lxml-difference- between-element-addnext-and-insert-functions
? Works just as documented:
root = etree.fromstring('<root><a/><b/><c/></root>') print etree.tostring(root, pretty_print=True) <root> <a/> <b/> <c/> </root>
child = root[0] help(root[0].addnext) Help on built-in function addnext:
addnext(...) addnext(self, element) Adds the element as a following sibling directly after this element. This is normally used to set a processing instruction or comment after the root node of a document. Note that tail text is automatically discarded when adding at the root level.
child.addnext(etree.Element('a_addnext')) print etree.tostring(root, pretty_print=True) <root> <a/> <a_addnext/> <b/> <c/> </root>
help(root[0].addprevious) Help on built-in function addprevious:
addprevious(...) addprevious(self, element) Adds the element as a preceding sibling directly before this element. This is normally used to set a processing instruction or comment before the root node of a document. Note that tail text is automatically discarded when adding at the root level.
child.addprevious(etree.Element('a_addprevious')) print etree.tostring(root, pretty_print=True) <root> <a_addprevious/> <a/> <a_addnext/> <b/> <c/> </root>
root.insert(root.index(child), etree.Element('root_insert')) print etree.tostring(root, pretty_print=True) <root> <a_addprevious/> <root_insert/> <a/> <a_addnext/> <b/> <c/> </root>
Maybe you just confused that addnext() and addprevious() add siblings and insert() inserts children?
root = etree.fromstring('<root><a/><b/><c/></root>') child = root[0] child.addprevious(etree.Element('before_a')) # equivalent: root.insert (root.index(child), etree.Element('before_a'))
child.addnext(etree.Element('after_a')) # equivalent: root.insert (root.index(child) + 1, etree.Element('after_a'))
Regards Holger Landesbank Baden-Wuerttemberg Anstalt des oeffentlichen Rechts Hauptsitze: Stuttgart, Karlsruhe, Mannheim, Mainz HRA 12704 Amtsgericht Stuttgart